24. Swap Nodes in Pairs

主要是看怎么分别对待Node总数是奇数还是偶数,其实也没什么区别的。。

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode res = head.next;
        
        ListNode first = head;
        ListNode second = head.next;
        ListNode next = head.next.next;
        
        while (next != null && next.next != null) {
            first.next = next.next;
            second.next = first;
            first = next;
            second = next.next;
            next = next.next.next;
        }
        
        first.next = next == null ? null:next;
        second.next = first;
        return res;
    }
}

好恨你。 让我心神不定。

posted @ 2016-11-04 08:07  哇呀呀..生气啦~  阅读(62)  评论(0)    收藏  举报