Thursday, April 25, 2019

Swap Nodes of Linked List without Copying


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

LeetCode 30 Day Challenge | Day 7 | Counting Elements

Given an integer array  arr , count element  x  such that  x + 1  is also in  arr . If there're duplicates in  arr , count them sepe...