LintCode | Swap Two Nodes in Linked List

http://www.lintcode.com/en/problem/swap-two-nodes-in-linked-list/#

先找到两个节点,再执行交换。有一个corner case须要注意:就是两个节点相邻的情况。

C++

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) {
        if (!head || !head->next) return head;
        ListNode dummy(0), *cur = &dummy; cur->next = head;
        ListNode *pre1 = NULL, *ptr1 = NULL, *pre2 = NULL, *ptr2 = NULL;
        while (cur) {
            if (cur->next) {
                if (cur->next->val == v1 || cur->next->val == v2) {
                    if (!pre1) { pre1 = cur; ptr1 = cur->next; }
                    else { pre2 = cur; ptr2 = cur->next; }
                }
            }
            cur = cur->next;
        }
        if (!pre1 || !pre2) return dummy.next;
        
        pre2->next = pre2->next->next;
        ptr2->next = pre1->next;
        pre1->next = ptr2;
        if (ptr1 == pre2) return dummy.next;
        
        ptr2->next = ptr2->next->next;
        ptr1->next = pre2->next;
        pre2->next = ptr1;
        
        return dummy.next;
    }
};
原文地址:https://www.cnblogs.com/ilovezyg/p/6375323.html