Sunday, January 11, 2015

[LeetCode]Swap Nodes in Pairs


很简单题,值得注意的是因为head会变,所以加一个sentinel节点,sentinel节点都能很优雅地解决head需要改变的问题。另外要注意的是更新curr的时候,由于在swap的时候,curr的为止变了,所以不能用curr = curr.next.next。

代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode pre = sentinel;
ListNode curr = head;
while (curr != null && curr.next != null) {
pre.next = swap(curr, curr.next);
pre = pre.next.next;
curr = pre.next;
}
return sentinel.next;
}
private ListNode swap(ListNode l1, ListNode l2) {
l1.next = l2.next;
l2.next = l1;
return l2;
}
}
view raw swap nodes.java hosted with ❤ by GitHub

No comments:

Post a Comment