24. Swap Nodes in Pairs
2016-09-13 21:13
246 查看
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.
时间复杂度:O(N)
思路: 从前往后,依次交换相邻的2个node,注意的是节点的交换过程.
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode start=new ListNode(0);
start.next=head;
ListNode temp=start;
ListNode p1,p2;
while(temp.next!=null&&temp.next.next!=null){
p1=temp.next;
p2=p1.next;
temp.next=p2;
p1.next=p2.next;
p2.next=p1;
temp=p1;
}
return start.next;
}
递归解法:: 求解从第一个开始的list和求解从第3个开始的list步骤是一样的,因此可以使用递归;
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode start=head.next;
head.next=swapPairs(head.next.next);
start.next=head;
return start;
}
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.
时间复杂度:O(N)
思路: 从前往后,依次交换相邻的2个node,注意的是节点的交换过程.
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode start=new ListNode(0);
start.next=head;
ListNode temp=start;
ListNode p1,p2;
while(temp.next!=null&&temp.next.next!=null){
p1=temp.next;
p2=p1.next;
temp.next=p2;
p1.next=p2.next;
p2.next=p1;
temp=p1;
}
return start.next;
}
递归解法:: 求解从第一个开始的list和求解从第3个开始的list步骤是一样的,因此可以使用递归;
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode start=head.next;
head.next=swapPairs(head.next.next);
start.next=head;
return start;
}
相关文章推荐
- NodeJS 使用Socket.IO实例
- Ubuntu16.04 32位桌面版安装nodejs
- LeetCode 24:Swap Nodes in Pairs
- node生成图形验证码
- 关于YARN Node Labels的一点理解
- webstorm 新建node项目
- HDFS的关键组件:NameNode/ DataNode
- MapReduce任务Namenode DataNode Jobtracker Tasktracker之间的关系
- 搭建nodejs开发环境
- 【Hadoop】Hadoop DataNode节点超时时间设置
- Node.Js教程
- Node.js
- Node.Js Stream(流)-(三)
- cordova 'buffer' 'nodeName' 错误处理
- Node.js net模块
- Node.Js Stream(流)-(二)
- Node.Js Stream(流)-(一)
- node的模块系统
- hadoop2.0的datanode多存储硬盘设置数据副本存放策略
- 浅谈JS之tagNaem和nodeName