24. Swap Nodes in Pairs
2016-01-06 22:10
393 查看
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.
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.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null) return null; ListNode fakehead = new ListNode(0); fakehead.next = head; ListNode p = fakehead; ListNode q = p.next; while(p.next != null && q.next != null){ p.next = q.next; q.next = q.next.next; p.next.next = q; p = p.next.next; q = q.next; } return fakehead.next; } }
相关文章推荐
- 9. Remove Nth Node From End of List
- Myeclipse 10 无法安装SVN或者Node.js
- node.js
- nodejs 参数默认值
- nodejs 格式化输出字符串
- NodeJS服务器端平台实践记录
- WebForm中创建树节点TreeNode
- nodejs模块 node-odata
- node开发学习(1)
- Nodejs源码分析之Console
- 使用apidoc 生成Restful web Api文档
- node实现watcher的困境
- Nodejs 学习01:如何写一个模块
- Express+Socket.IO 搭建即时聊天
- node测试相关工具
- 《nodejs开发指南》微博实例express4.x版
- 简单总结iNode和block知识
- nodejs 设置proxy
- nodejs+mongoose简单关联+增删改查
- 关于Node的async包的一点笔记