5/30/2014

22. Swap Nodes in Pairs

/**
 * 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) {
        if (head==null) return null;
       
        ListNode res = new ListNode(0);
        res.next = head;
        head = res;
       
        while (res.next!=null && res.next.next!=null) {
            ListNode p1 = res.next;
            ListNode p2 = res.next.next;
           
            p1.next = p2.next;
            p2.next = p1;
            res.next = p2;
            res = p1;
        }
       
        return head.next;
    }
}

1 条评论: