Leetcode-第24题:Swap Nodes in Pairs

题目:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

代码:

def swapPairs(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    pre = None
    p1 = head
    while p1!=None and p1.next!=None:
        p2 = p1.next
        t = p2.next
        p2.next = p1
        p1.next = t
        if pre == None:
            head = p2
        else:
            pre.next = p2
        pre = p1
        p1 = p1.next
    return head

你可能感兴趣的:(Leetcode-第24题:Swap Nodes in Pairs)