LintCode "Swap Two Nodes in Linked List"

时间:2024-08-25 20:05:32

Nothing special. Just take care of corner cases.

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) return head; ListNode *p1 = nullptr, *p1p = nullptr, *p1n = nullptr;
ListNode *p2 = nullptr, *p2p = nullptr, *p2n = nullptr; // Pass 1: Find nodes
//
ListNode *prev = nullptr, *p = head, *next = p->next;
while(p)
{
if(p->val == v1 || p->val == v2)
{
if(!p1)
{
p1 = p;
p1p = prev;
p1n = next;
}
else
{
p2 = p;
p2p = prev;
p2n = next;
}
}
// move on
prev = p;
p = next;
next = next?next->next:nullptr;
}// while if(!p1 || !p2)
return head; // Step 2:
//
ListNode *ret = head;
if(p1 == head)
{
ret = p2;
} if (p1n == p2) // adjacent
{
if(p1p)
p1p->next = p2;
p2->next = p1;
p1->next = p2n;
}
else
{
if(p1p)
p1p->next = p2;
p2->next = p1n;
p2p->next = p1;
p1->next = p2n;
} return ret;
}
};