算法系列——Swap Nodes in Pairs
来源:互联网 发布:怎么在淘宝上拿货的 编辑:程序博客网 时间:2024/06/05 02:45
题目描述
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.
解题思路
这个题目稍微复杂一点。如下图所示,我们引入虚拟头结点,并且利用4个指针p,node1,node2,next,分别表示 描述 前驱,交换结点1,交换结点2和后继。更新这四个结点的值即可。
程序实现
public class Solution { public ListNode swapPairs(ListNode head) { if(head==null) return null; ListNode dummyHead=new ListNode(-1); dummyHead.next=head; ListNode p=dummyHead; while(p.next!=null&&p.next.next!=null){ ListNode node1=p.next; ListNode node2=p.next.next; ListNode next=node2.next; node2.next=node1; node1.next=next; p.next=node2; p=node1; } return dummyHead.next; }}
阅读全文
0 0
- 算法系列——Swap Nodes in Pairs
- LeetCode算法题——24. Swap Nodes in Pairs
- 算法 Swap Nodes in Pairs
- LeetCode——Swap Nodes in Pairs
- LeetCode——Swap Nodes in Pairs
- <24>—— Swap Nodes in Pairs
- LeetCode—Swap Nodes in Pairs
- Algorithms—24.Swap Nodes in Pairs
- 【Leetcode长征系列】Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- 一些PHP性能的优化
- 求二进制中1的个数
- 最全面的SQL语句总结 <精品推荐>
- HDU 5038
- Discuz之Windows下PHP环境的基本搭建(纯手动搭建)
- 算法系列——Swap Nodes in Pairs
- 【JZOJ5229】【GDOI2018模拟7.14】小奇的糖果
- 在windows下的qt5.7.1 的纯C或C++项目命令行中文乱码、无法编译等问题解决
- 【文献阅读/翻译...】bayesian compression for deep learning深度学习中的贝叶斯压缩
- Spark的Dataset操作(三)-分组,聚合,排序
- BZOJ1878: [SDOI2009]HH的项链(莫队)
- JS倒计时效果+数字图片
- Java设计模式——单例模式
- 【NOIP2013模拟11.6A组】灵能矩阵(pylon)