leetcode之Swap Nodes in Pairs

来源:互联网 发布:php大数据处理 编辑:程序博客网 时间:2024/06/14 00:43
这题要求是常数空间,不能修改值,只能修改node,所以直接在node上进行操作。代码如下:
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def swapPairs(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head:            if head.next:                b = head.next                head.next = head.next.next                b.next = head                head = b                print head.val                left = head.next                while left.next and left.next.next:                    b = left.next                    left.next = b.next                    c = left.next.next                    left.next.next = b                    b.next = c                    left = left.next.next        return head

0 0
原创粉丝点击