边工作边刷题:70天一遍leetcode: day 37-1

Swap Nodes in Pairs

# 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
        cur = head
        pre = dummy
        while cur and cur.next:
            # swap
            next = cur.next.next
            cur.next.next=cur
            pre.next = cur.next
            cur.next = next
            
            pre = cur
            cur = next
            
        return dummy.next
posted @ 2016-04-11 11:50  absolute100  阅读(92)  评论(0编辑  收藏  举报