【leetcode❤python】24. Swap Nodes in Pairs

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

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy=ListNode(0)
        dummy.next=head
        pre,cur=dummy,head
        
        while cur and cur.next: #cur=1,cur.next=2
            pre.next=cur.next       #dummy--->2
            cur.next=cur.next.next  #1-->3
            pre.next.next=cur       #2-->1
            pre,cur=cur,cur.next    #pre=1,cur=3
        return dummy.next

posted @ 2016-10-12 17:03  火金队长  阅读(120)  评论(0编辑  收藏  举报