LeetCode : Swap Nodes in Pairs [java]
来源:互联网 发布:手机防盗报警软件 编辑:程序博客网 时间:2024/06/14 01:13
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.
思路:纯链表操作,使用额外节点记录"指针",主要需要记录的是:当前交换的两个节点,两个节点后的节点(如果有的话)以及构建新链表的"指针".
/** * 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) {ListNode myHead = new ListNode(-1);ListNode myPointer = myHead;while (head != null) {ListNode next2 = head.next;if (next2 == null) {myPointer.next = head;break;} else {next2 = next2.next;ListNode qian = head;ListNode hou = head.next;qian.next = hou.next;hou.next = qian;myPointer.next = hou;myPointer = myPointer.next.next;head = next2;}}return myHead.next; }}
1 0
- [Leetcode] Swap Nodes in Pairs (Java)
- leetcode Swap Nodes in Pairs java实现
- [LeetCode][Java] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs [java]
- 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)
- Swap Nodes in Pairs leetcode java
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- CodeForces 630 N. Forecast(大水题)
- UICollectionView 的布局
- DataPicker 和 TimePicker
- eclipse常用插件,最实用的插件
- struts2-spring-hibernate
- LeetCode : Swap Nodes in Pairs [java]
- HUD 1003/HDU 1081:动态规划之最大子序列和+最大矩阵和
- 网络性能评价方法
- 对class、superclass、super你了解多少?
- 我的博客
- MyBatis动态SQL之一使用 if 标签和 choose标签
- Kalman Filter的推导与应用(二)
- 算法训练 结点选择
- 处理大并发之一 对异步非阻塞的理解