Sunday, September 7, 2014

Leetcode: Swap Nodes in Pairs @Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        dummy=ListNode(0)
        dummy.next=head
        pre=dummy
        crt=head
        while crt and crt.next:
            temp=crt.next.next
            pre.next=crt.next
            crt.next=temp
            pre.next.next=crt
            pre=crt
            crt=crt.next
        return dummy.next

No comments :

Post a Comment