Thursday, November 5, 2015

[leetcode]Swap Nodes in Pairs

其实头脑冷静下来 把图画一画 整条题很简单的
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode current = head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode previous = dummy;
        while (current != null && current.next != null){
            previous.next = current.next;
            ListNode next = current.next.next;
            current.next.next = current;
            current.next = null;
            previous = current;
            current = next;
        }
        
        if (current != null){
            previous.next = current;
        }
        
        return dummy.next;
    }
}

No comments:

Post a Comment