LeetCode: Swap Nodes in Pairs 解题报告
2014-11-29 20:23
471 查看
[b]Swap Nodes in Pairs [/b]
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.
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/SwapPairs3.java
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.
// Solution 3: the iteration version. public ListNode swapPairs3(ListNode head) { // 如果小于2个元素,不需要任何操作 if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; // The node before the reverse area; ListNode pre = dummy; while (pre.next != null && pre.next.next != null) { ListNode next = pre.next.next.next; ListNode tmp = pre.next; pre.next = pre.next.next; pre.next.next = tmp; tmp.next = next; // move forward the pre node. pre = tmp; } return dummy.next; }
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/SwapPairs3.java
相关文章推荐
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [Leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- leetcode解题报告24. Swap Nodes in Pairs
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- [LeetCode] Swap Nodes in Pairs 解题报告
- [LeetCode] Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- Swap Nodes in Pairs LeetCode 解题报告
- LeetCode解题报告—— Swap Nodes in Pairs & Divide Two Integers & Next Permutation
- LeetCode解题报告--Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs 解题报告
- leetcode解题方案--024--Swap Nodes in Pairs
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- Swap Nodes in Pairs ——解题报告
- [leetcode javascript解题]Swap Nodes in Pairs
- leetcode: Swap Nodes in Pairs
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- leetcode swap nodes in pairs