您的位置:首页 > Web前端 > Node.js

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.

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: