24. Swap Nodes in Pairs -leetcode-java
来源:互联网 发布:西安504所硕士待遇知乎 编辑:程序博客网 时间:2024/06/06 00:20
今天一下午被这道题困惑好久,也是够笨呀。
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
- 24. Swap Nodes in Pairs -leetcode-java
- (Java)LeetCode-24. Swap Nodes in Pairs
- [LeetCode-Java]24. Swap Nodes in Pairs
- [leetcode]24. Swap Nodes in Pairs(java)
- [LeetCode] 24. Swap Nodes in Pairs java
- [Leetcode] Swap Nodes in Pairs (Java)
- leetcode Swap Nodes in Pairs java实现
- [LeetCode][Java] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs [java]
- leetcode Swap Nodes in Pairs(Java)
- Swap Nodes in Pairs leetcode java
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- LeetCode --- 24. Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- 【LeetCode】24.Swap Nodes in Pairs
- [leetcode] 24.Swap Nodes in Pairs
- 回调机制
- iBatis Date 类型 时分秒丢失(精度丢失)问题
- bzoj4517 sdoi2016 排列计数 错排
- [POJ 3190] Stall Reservations (区间贪心)
- python快速统计一个文件包含的单词数
- 24. Swap Nodes in Pairs -leetcode-java
- PHP命名空间(Namespace)的使用详解
- 使用Jenkins plugin遇到问题调试方法
- 2016百度之星资格赛——B
- Echart3 如何获取地图的经纬度与页面坐标
- Android 调用Google Map api v3路由两点间距离、时间以及解析方式
- C++走向远洋——55(项目一3、分数类的重载、>><<的重载)
- C语言存储空间管理和链表杂记
- Android开发实现高德地图定位详解