Swap Nodes in Pairs
2015-10-21 22:08
483 查看
Given a linked list, swap every two adjacent nodes and return its head.
样例
Given 1->2->3->4, you should return the list as 2->1->4->3.
样例
Given 1->2->3->4, you should return the list as 2->1->4->3.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @return a ListNode */ public ListNode swapPairs(ListNode head) { // Write your code here ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while(head.next != null && head.next.next != null){ ListNode n1 = head.next, n2 = head.next.next; //head->n1->n2... //=>head->n2->n1... head.next = n2; n1.next = n2.next; n2.next = n1; head = n1; } return dummy.next; } }
相关文章推荐
- nodejs字符与字节之间的转换
- 如何提高NodeJS程序的稳定性
- ListNode
- XML——SelectSingleNode 获取有命名空间的节点的值
- NodeJS学习_1
- 【Glassfish】GlassFish中Domain、DAS、cluster、 instance以及node agent之间的关系
- nodejs图片转换字节保存
- nodejs实战express笔记之实现用户和文章页面
- Nodejs 模块
- 使用 AngularJS & NodeJS 实现基于 token 的认证应用
- Node入门训练【7】【用express写出hello world】
- node.js学习网址
- Understanding the node.js event loop
- LeetCode 19 Remove Nth Node From End of List(从列表尾部删除第N个结点)(*)
- Node入门训练【6】【将data写本地log】
- nodeJS实现图片上传和展示
- Node入门训练【4】【根据url路径参数打印相应盘符目录】
- nodejs实战express之使用Markdown
- 自己写的一本nodejs小教程
- LeetCode 19: Remove Nth Node From End of List