C++ Code:
void swap_nodes(Node **headPtr, int a, int b){
if(a == b || !headPtr || !(*headPtr))
return;
Node *curr = *headPtr;
Node *prev = nullptr;
Node *nodeA = nullptr;
Node *nodeB = nullptr;
Node *prevA = nullptr;
Node *prevB = nullptr;
while (curr) {
if(curr->data == a){
nodeA = curr;
prevA = prev;
} else if(curr->data == b){
nodeB = curr;
prevB = prev;
}
prev = curr;
curr = curr->next;
}
if(!nodeA || !nodeB)
return;
if(prevA){
prevA->next = nodeB;
} else { // nodeA is head
*headPtr = nodeB;
}
if(prevB){
prevB->next = nodeA;
} else { // nodeB is head
*headPtr = nodeA;
}
Node *tmp = nodeA->next;
nodeA->next = nodeB->next;
nodeB->next = tmp;
}
Detailed explanation is available on youtube:
Subscribe toKnowledgeCenter
No comments:
Post a Comment