您的位置:首页 > Web前端 > Node.js

24. Swap Nodes in Pairs

2017-01-11 12:53 260 查看
题意: 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode