leetcode: 24. Swap Nodes in Pairs

来源:互联网 发布:淘宝评论显示有违禁词 编辑:程序博客网 时间:2024/06/18 17:24

Problem

# 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.## Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

AC

class ListNode():    def __init__(self, x):        self.val = x        self.next = Noneclass Solution():    def swapPairs(self, x):        cur = dummy = ListNode(0)        tmp, step = None, 1        while x:            if step % 2:                tmp = ListNode(x.val)            else:                cur.next, cur.next.next = ListNode(x.val), tmp                cur, tmp = cur.next.next, None            x, step = x.next, step + 1        if tmp:            cur.next = tmp        return dummy.nextif __name__ == "__main__":    x, x.next, x.next.next, x.next.next.next = ListNode(1), ListNode(2), ListNode(3), ListNode(4)    res = Solution().swapPairs(x)    assert '{0}->{1}->{2}->{3}'.format(res.val, res.next.val, res.next.next.val, res.next.next.next.val) \           == '2->1->4->3'
原创粉丝点击