Swapping Nodes on a single linked list

前端 未结 8 1075
说谎
说谎 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.

提交回复
热议问题