24. Swap Nodes in Pairs -leetcode-java
2016-05-26 18:54
609 查看
今天一下午被这道题困惑好久,也是够笨呀。
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
题意就是交换一个链表每两个相邻节点。
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
// ListNode fakehead=null;
ListNode fakehead=new ListNode(-1);//注意这里要初始化赋值,-1这个数是任意的哈
fakehead.next=head;
ListNode ptr1=fakehead;
ListNode ptr2=head;
ListNode nextstart;
while(ptr2!=null && ptr2.next!=null){
nextstart=ptr2.next.next;
ptr2.next.next=ptr2;//对应图的第二步
ptr1.next=ptr2.next;//对应图的第三步
ptr2.next=nextstart;//对应图的第四步
ptr1=ptr2;//上面交换完成了,这里指针开始挪动到下一位置了
ptr2=ptr2.next;//指针挪动
}
return fakehead.next;
}
}
画了下图……
交换过程:
![](https://img-blog.csdn.net/20160526183854001?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
注意ptr1 ptr2就是两个指针,指针本次任务完成了,就接着移动,该指向下一轮啦。整个链表的头结点的使命,交给fakehead。也就是fakehead.next也就是常说的dummy。用这个假节点,next指向头结点,以便于保持和后续的节点处理一致。方便操作。
参考资料:
博客园-Swap Nodes in Pairs
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.
题意就是交换一个链表每两个相邻节点。
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
// ListNode fakehead=null;
ListNode fakehead=new ListNode(-1);//注意这里要初始化赋值,-1这个数是任意的哈
fakehead.next=head;
ListNode ptr1=fakehead;
ListNode ptr2=head;
ListNode nextstart;
while(ptr2!=null && ptr2.next!=null){
nextstart=ptr2.next.next;
ptr2.next.next=ptr2;//对应图的第二步
ptr1.next=ptr2.next;//对应图的第三步
ptr2.next=nextstart;//对应图的第四步
ptr1=ptr2;//上面交换完成了,这里指针开始挪动到下一位置了
ptr2=ptr2.next;//指针挪动
}
return fakehead.next;
}
}
画了下图……
交换过程:
注意ptr1 ptr2就是两个指针,指针本次任务完成了,就接着移动,该指向下一轮啦。整个链表的头结点的使命,交给fakehead。也就是fakehead.next也就是常说的dummy。用这个假节点,next指向头结点,以便于保持和后续的节点处理一致。方便操作。
参考资料:
博客园-Swap Nodes in Pairs
相关文章推荐
- 【深入浅出Node.js系列八】一个基于Node.js完整的Web应用实战
- 【深入浅出Node.js系列七】Connect模块解析
- 【深入浅出Node.js系列六】Buffer那些事儿
- 【深入浅出Node.js系列五】初探Node.js的异步I/O实现
- nodejs 热更新
- 【深入浅出Node.js系列四】Node.js的事件机制
- 【深入浅出Node.js系列三】深入Node.js的模块机制
- 【深入浅出Node.js系列二】Node.js&NPM的安装与配置
- 【深入浅出Node.js系列一】什么是Node.js
- Nodejs 中常见的加密算法:MD5,RSA
- Nodejs in Visual Studio Code 14.IISNode与IIS7.x
- 19. Remove Nth Node From End of List(Linked List)
- Nodejs学习笔记(三)
- ROS的节点(NODE)
- AVA实践:面向未来的Node.js测试运行器
- node更新版本后sass无法编译解决办法
- node.js学习
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- 25. Reverse Nodes in k-Group
- leetcode---Swap Nodes in Pairs