Leetcode Swap Nodes in Pairs
2015-11-14 02:15
651 查看
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.
然后就进行正常的链表交换,和指针挪动就好。
当链表长度为奇数时,cur.next可能为null;
当链表长度为偶数时, cur可能为null。
所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next。
Java code:
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html
2. http://www.cnblogs.com/springfor/p/3862030.html
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.
解题思路:
需要运用fakehead来指向原指针头,防止丢链,用两个指针,pre始终指向需要交换的pair的前面一个node,cur始终指向需要交换的pair的第一个node。然后就进行正常的链表交换,和指针挪动就好。
当链表长度为奇数时,cur.next可能为null;
当链表长度为偶数时, cur可能为null。
所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next。
Java code:
public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null){ return head; } ListNode fakehead = new ListNode(0); fakehead.next = head; ListNode pre = fakehead; ListNode cur = head; while(cur!= null && cur.next != null) { pre.next = cur.next; cur.next = cur.next.next; pre.next.next = cur; pre = cur; cur = cur.next; } return fakehead.next; } }
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html
2. http://www.cnblogs.com/springfor/p/3862030.html
相关文章推荐
- 使用nvm做nodejs的版本管理
- LeetCode19:Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List
- LeetCode 24_Swap Nodes in Pairs
- Ubuntu下安装Node.js
- NodeJs端口被占用的情况
- 删除 windows 下 node_modules 过深的目录
- 【leetcode】【24】Swap Nodes in Pairs
- 初识node.js
- node -e "require('nan')" npm 安装 tty.js 时报错 ,解决方法
- 关于机房交换机故障导致HDFS NameNode挂掉的问题
- 一步步学习使用node和express开发web应用(二)——npm介绍,express的引入,路由机制
- Node.js
- Node.js cookie-parser
- 一步步学习使用node和express开发web应用(一)——node简介、开发环境及构建最简web应用
- PRVF-0002 : Could not retrieve local nodename 报错解决
- node文章
- node.js回调函数之阻塞调用与非阻塞调用
- Hadoop启动namenode失败,端口号冲突问题解决
- Swap Nodes in Pairs