I am learning to swap nodes. The problem comes from Leetcode:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Now, obviously my attempt is NOT working and I am confused(as usual) why temp in the code gets updated.
head = [1,2,3,4,5,6]
def swapPairs(self):
temp=self
print("orig %s", (temp))
for x in range(len(self)):
if x%2!=0:
print("temp odd before %s", (temp))
self[x]=temp[x-1]
print("temp odd after %s", (temp))
else:
print("temp even before %s", (temp))
self[x]=temp[x+1]
print("temp even after %s", (temp))
return self
I see that when I am printing temp the values of it are getting updated. But it is on the right side of equation.
How can that happen ?
The Second problem is the actual problem of swapping node.
The odd elements are switched with the previous even element.
Please advise.
Thank You