educative.io

In node_swap implementation, do we really need to swap the node objects?

In class LinkedList, method swap_nodes(self, key_1, key_2), can’t we simply swap the values once we find the nodes containing the keys? For example, we can simply do

curr_1.data = key_2
curr_2.data = key_1

and not mess with the prev and .next assignments etc?

The results are the same using the test cases included.

yeah I thought of the same situation if we just change values in the node it would be fine why do we need to change all the references seems like extra work no

Yeah Exactly i did the same thing and it works just fine…

    def swap_nodes(self, value_1, value_2):
    if value_1 == value_2:
        return
    current_node_1 = self.head
    while current_node_1 and current_node_1.data != value_1:
        current_node_1 = current_node_1.next

    current_node_2 = self.head
    while current_node_2 and current_node_2.data != value_2:
        current_node_2 = current_node_2.next

    if current_node_1 and current_node_2:
        current_node_1.data, current_node_2.data = current_node_2.data, current_node_1.data

    return

Hello, both are valid approaches. HOWEVER, it depends on what the question or interviewer asks. In an interview it would be very good to clarify if you can just swap the values or must your actual swap the nodes and their references, two very different things that can make a big impact.

So it’s best to understand both methods I guess.

I solved this LeetCode problem after learning this module, it’s a very good question to test your learning. I used the swap values method and all tests passed, so it depends on what the interviewer wants. Hope this helps :grinning: