2014年2月11日星期二

LeetCoder - Send Feedback Swap Nodes in Pairs

 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.

/**
 * 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 || head.next==null) {
            return head;
        }
        ListNode p0 = null;
        ListNode p1 = head;
        ListNode p2 = head.next;
        ListNode p3 = p2.next;
        ListNode newHead = p2;
        while(true) {
            if(p0!=null) {
                p0.next = p2;
            }
            p2.next = p1;
            p1.next = p3;
            if(p3==null || p3.next==null) {
                break;
            }
            p0 = p1;
            p1 = p3;
            p2 = p3.next;
            p3 = p3.next.next;
        }
        return newHead;
    }
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode p1 = head;
       
        while (p1 != null && p1.next != null) {
            ListNode p2 = p1.next;
            ListNode tmpP = p2.next;
           
            pre.next = p2;
            p2.next = p1;
            p1.next = tmpP;
           
            pre = p1;
            p1 = tmpP;
        }
        return dummy.next;
    }
}

没有评论:

发表评论