LeetCode#24 Swap Nodes in Pairs

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也发现不了)

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

 1     # @param {ListNode} head
 2     # @return {ListNode}
 3     def swapPairs(self, head):
 4         return self.recur(head, head.next) if head else None
 5 
 6     def recur(self, p, q):
 7         if q==None:
 8             return p
 9         tmp=q.next
10         q.next=p
11         p.next=self.recur(tmp, tmp.next) if tmp else None
12         return q

 

posted @ 2015-08-01 20:25  曾可爱  阅读(123)  评论(0编辑  收藏  举报