Swap Two Nodes in Linked List

题目:

Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.

Given 1->2->3->4->null and v1 = 2, v2 = 4.
Return 1->4->3->2->null.

分析:

每次做都错,就是记不住两个node连续这种corner case!!!!!!!

解法:

public class Solution {
    /**
     * @param head a ListNode
     * @oaram v1 an integer
     * @param v2 an integer
     * @return a new head of singly-linked list
     */
    public ListNode swapNodes(ListNode head, int v1, int v2) {
        // Write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode prev1 = dummy;
        ListNode curr1 = head;
        while (curr1 != null) {
            if ( curr1.val == v1 || curr1.val == v2 ) {
                break;
            } else {
                prev1 = prev1.next;
                curr1 = curr1.next;
            }
        }
        if (curr1 == null) {
            return head;
        }

        ListNode prev2 = prev1.next;
        ListNode curr2 = curr1.next;
        while (curr2 != null) {
            if ( curr2.val == v1 || curr2.val == v2 ) {
                break;
            } else {
                prev2 = prev2.next;
                curr2 = curr2.next;
            }
        }
        if (curr2 == null) {
            return head;
        }

        if (curr1.next == curr2) {
            ListNode next2 = curr2.next;
            prev1.next = curr2;
            curr2.next = curr1;
            curr1.next = next2;
        } else {
            ListNode next1 = curr1.next;
            ListNode next2 = curr2.next;
            prev1.next = curr2;
            curr2.next = next1;
            prev2.next = curr1;
            curr1.next = next2;
        }
        return dummy.next;

    }
}

results matching ""

    No results matching ""