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
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Solution: 题目要求不能直接交换链表结点的元素值。(虽然跑起来OJ也发现不了)
用递归实现起来是比较简单直观的,无需构造首节点什么的。这里要注意处理奇数个节点的情况。
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
相关文章推荐
- leetcode--Count Complete Tree Nodes
- Node.js初体验之入门(二)
- Node.js初体验之入门(一)
- 【leetCode】Swap Nodes in Pairs
- 一棵完全二叉树,找到每个节点在这一层右边的点(Populating Next Right Pointers in Each Node)
- (easy)LeetCode 237.Delete Node in a Linked List
- win8.1 JMeter启动时显示Could not open/create prefs root node Software\JavaSoft\Prefs at root
- Node.js 使用 child_process 实现多进程
- suse10下nodejs安装时提示openssl not found的问题解决办法 1、首先确认openssl有没有安装,使用命令 openssl version 2、明明已经安装了openssl
- nodejs使用笔记
- nodejs 模块安装与使用
- MonoDevelop 常用设置和快捷键
- nodejs随记01
- nodejs安装express
- nodejs windows环境安装
- Delete Node in a Linked List Java LeetCode
- LeetCode_237 Delete Node in a Linked List
- Cannot delete .... . Name node is in safe mode
- hadoop启动后jps查看总是不显示namenode进程,然后重新格式化hdfs
- node-odata: ASP.NET WEB API OData的替代品