Swapping Nodes on a single linked list

前端 未结 8 908
说谎
说谎 2020-12-03 16:11

I am trying to make a swapNode function that can take any two nodes and swap them. I\'ve made an algorithm that works if they\'re at least 2 nodes away, but I c

相关标签:
8条回答
  • 2020-12-03 16:48

    In most real-life scenarios, swapping the values will be the best solution:

    void swapNode(call * &head, call * &first, call * &second) {
        // swap values, assuming the payload is an int:
        int tempValue = first->value;
        first->value = second->value;
        second->value = tempValue;
    }
    

    If that's not allowed, then you want to do a similar-style swap on the ->next instead of the ->value component. And then do another swap on the firstPrev->next and secondPrev->next components. Watch out for the special case where first or second == head.

    0 讨论(0)
  • 2020-12-03 16:51

    You will have to also swap the next component of the previous node, otherwise the linked list will not remain joined together. Note that my struct is called node.

    int swapNode( node *&head * &first, node * &second)
    {
         //first we will declare the 
         //previous of the swapping nodes
         node *firstprev=NULL;
         node*secprev=NULL;
         node*current=head;
         //set previous first
         while(current->next!=first)
         {
            current=current->next;
         }
         firstprev=current;
         //seting 2nd previous
         while(current->next!=second)
         {
            current=current->next;
         }
    
        // swap values, assuming the payload is an int:
        int tempValue = first->value;
        first->value = second->value;
        second->value = tempValue;
        //swaping next of the nodes
        firstprev->next=second;
        secprev->next=first;
        return; 
    }
    
    0 讨论(0)
提交回复
热议问题