码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#24 Swap Nodes in Pairs

时间:2015-08-01 21:50:14      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode#24 Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/acetseng/p/4694607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!