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

Leetcode Swap Nodes in Pairs

2015-11-14 02:15 651 查看
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.

解题思路:

需要运用fakehead来指向原指针头,防止丢链,用两个指针,pre始终指向需要交换的pair的前面一个node,cur始终指向需要交换的pair的第一个node。

然后就进行正常的链表交换,和指针挪动就好。

当链表长度为奇数时,cur.next可能为null;

当链表长度为偶数时, cur可能为null。

所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next。

Java code:

public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode fakehead = new ListNode(0);
fakehead.next = head;

ListNode pre = fakehead;
ListNode cur = head;

while(cur!= null && cur.next != null) {
pre.next = cur.next;
cur.next = cur.next.next;
pre.next.next = cur;
pre = cur;
cur = cur.next;
}
return fakehead.next;
}
}


Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html
2. http://www.cnblogs.com/springfor/p/3862030.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: