24. Swap Nodes in Pairs
2016-07-16 22:07
369 查看
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.
两个一组,保存好前驱,交换完毕继续推进。开头也要换,所以增加一个冗余节点作为辅助。
public class Solution {
public static ListNode swapPairs(ListNode head)
{
if(head==null)
return head;
ListNode dummy=new ListNode(6);
dummy.next=head;
ListNode p1=head;
ListNode p2=head.next;
ListNode prev=dummy;
while(p2!=null)
{
p1.next=p2.next;
p2.next=p1;
prev.next=p2;
prev=p1;
p1=p1.next;
if(p1!=null)
p2=p1.next;
else {
break;
}
}
return dummy.next;
}
}
还有递归方法: https://discuss.leetcode.com/topic/4351/my-accepted-java-code-used-recursion
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
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.
两个一组,保存好前驱,交换完毕继续推进。开头也要换,所以增加一个冗余节点作为辅助。
public class Solution {
public static ListNode swapPairs(ListNode head)
{
if(head==null)
return head;
ListNode dummy=new ListNode(6);
dummy.next=head;
ListNode p1=head;
ListNode p2=head.next;
ListNode prev=dummy;
while(p2!=null)
{
p1.next=p2.next;
p2.next=p1;
prev.next=p2;
prev=p1;
p1=p1.next;
if(p1!=null)
p2=p1.next;
else {
break;
}
}
return dummy.next;
}
}
还有递归方法: https://discuss.leetcode.com/topic/4351/my-accepted-java-code-used-recursion
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
相关文章推荐
- 19. Remove Nth Node From End of List
- nodejs
- [INS-41112]Specified network interface doesnt maintain connectivity across cluster nodes
- leetcode_c++:链表:Reverse Nodes in k-Group(025)
- async whilst使用注意
- node package有两种依赖
- LeetCode - 61. Rotate List
- IDE-Sublime【3】-配置Node.js开发环境
- 认识DOM的三大节点:元素节点,文本节点,属性节点以及nodeName,nodeType,nodeValue的区别
- 【旧代码整理】Nodejs的另类用法
- 在Node.js环境中使用OSS Javascript SDK来访问OSS服务
- node.js中的express框架安装
- Populating Next Right Pointers in Each Node
- Nodejs之MEAN栈开发(七)---- 用Angular创建单页应用(下)
- LeetNode--No.257--Binary Tree Paths
- Node.js新手必须知道的4个JavaScript概念
- nodejs安装一些模块报错
- nodejs群聊和私聊
- eetcode_c++:链表:Swap Nodes in Pairs(024)
- Nodejs初阶之express