Populating Next Right Pointers in Each Node II @ LeetCode (Python)
Search a 2D Matrix @ LeetCode (Python)

Swap Nodes in Pairs @ LeetCode (Python)

kitt posted @ 2014年3月21日 23:47 in LeetCode , 2545 阅读

Add a dummy node (aka header node), things will become easier.

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        dummyNode = ListNode(0) # add a dummy node to avoid special case
        dummyNode.next = head
        head = dummyNode
        prev = head
        curr = prev.next
        if curr == None: return
        succ = curr.next
        while curr and succ:
            curr.next = succ.next
            succ.next = curr
            prev.next = succ
            if curr.next:
                prev = curr
                curr = prev.next
                succ = curr.next
            else:
                break
        return head.next # note that we added a dummy node

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter