美文网首页Leetcode
24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

作者: oo上海 | 来源:发表于2016-08-07 23:34 被阅读30次

24. Swap Nodes in Pairs

题目:
https://leetcode.com/problems/swap-nodes-in-pairs/

难度 : Easy

看了hint,用loop做,每个node关系要弄清楚


class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head

        dummy = ListNode(-1)
        dummy.next = head
        
        cur = dummy

        while cur.next and cur.next.next:
            next_one, next_two, next_three = cur.next, cur.next.next, cur.next.next.next
            cur.next = next_two
            next_two.next = next_one
            next_one.next = next_three
            cur = next_one
        return dummy.next

相关文章

网友评论

    本文标题:24. Swap Nodes in Pairs

    本文链接:https://www.haomeiwen.com/subject/nlnlsttx.html