24. Swap Nodes in Pairs

来源:互联网 发布:ios存储数据的方法 编辑:程序博客网 时间:2024/06/16 08:14

题意: 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.

思路:这里有一点特别要说,python没有指针这个概念,所以这个头指针实际上就是第一个结点的一个成员变量,所以我在头结点之前,再建立一个结点,用于结点的交换,附代码:

def swapPairs(self, head):        h = ListNode(0)        h.next, p, f = head, head, h        while p and p.next:           q = p.next           f.next = q           p.next = q.next           q.next = p           f = p           p = p.next        return h.next
0 0
原创粉丝点击