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.

分析:

这道题目有个特别阴损的地方,intuitive的想,两个节点v1和v2如果不连续,那么写一段代码swap就好,然而如果连续的话,需要用不同的代码处理。注意这个switch,有三种情况,别漏。

解法:

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

        ListNode dummy(0);
        dummy.next = head;

        ListNode* prevV1 = NULL;
        ListNode* prevV2 = NULL;
        ListNode* curr = &dummy;

        while (curr->next != NULL) {
            if (prevV1 == NULL && curr->next->val == v1) {
                prevV1 = curr;
            }
            if (prevV2 == NULL && curr->next->val == v2) {
                prevV2 = curr;
            }
            curr = curr->next;
        }

        if (prevV1 == NULL || prevV2 == NULL) {
            return head;
        }

        ListNode* V1 = prevV1->next;
        ListNode* V2 = prevV2->next;
        if (prevV1->next == prevV2) {

            prevV1->next = V2;
            V1->next = V2->next;
            V2->next = V1;

        } else if (prevV2->next == prevV1) {

            prevV2->next = V1;
            V2->next = V1->next;
            V1->next = V2;

        } else {

            ListNode* nextV1 = V1->next;
            ListNode* nextV2 = V2->next;

            prevV1->next = V2;
            V2->next = nextV1;
            prevV2->next = V1;
            V1->next = nextV2;
        }
        return dummy.next;
    }
};

results matching ""

    No results matching ""