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

LeetCode#24 Swap Nodes in Pairs

2015-08-01 20:25 567 查看
Problem Definition:

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.

Solution: 题目要求不能直接交换链表结点的元素值。(虽然跑起来OJ也发现不了)

用递归实现起来是比较简单直观的,无需构造首节点什么的。这里要注意处理奇数个节点的情况。

# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
return self.recur(head, head.next) if head else None

def recur(self, p, q):
if q==None:
return p
tmp=q.next
q.next=p
p.next=self.recur(tmp, tmp.next) if tmp else None
return q
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: