I have a singly-linked-list, L, and create a pointer to this list P. It seems like sometimes modifying P changes the actual list, while other times modifying P does nothing to the actual list L and only changes what P is pointing to.
Suppose I create a pointer to L, P = L (in python). Doing something like P = P.next leaves L unchanged, but P.next = P.next.next changes L. Similarly, changing the actual data stored in the list by modifying P.data actually changes L.data.
Why does this happen? I feel like I'm missing something fundamental about pointers/references.
class Node:
def __init__(self, val):
self.val = val
self.next = None
def addNode(self, val):
root = self
while root.next is not None:
root = root.next
root.next = Node(val)
def iterateLL(self):
root = self
print
while root is not None:
print(str(root.val) + " ", end="")
root = root.next
print()
if __name__ =="__main__":
L = Node(1)
L.addNode(2)
L.addNode(3)
L.addNode(4)
# iterate through list and print:
L.iterateLL()
# changing value of pointer does not affect L
P = L
P = P.next
L.iterateLL() # L is unchanged
# changing "next" value of pointer does affect L
P = L
P.next = P.next.next
L.iterateLL() # now we've skipped node 2
# changing data of pointer does affect L
P = L
P.val = 10
L.iterateLL()
The above code executes with the following output (first line shows the original linked list, second line shows that the list is unchanged following a change to the pointer P, while the third and fourth lines show that the list is changed)
1 2 3 4
1 2 3 4
1 3 4
10 3 4
What's going on here? Why does changing P not affect L, but changing P.next and P.val do? If all of these actions behaved the same way, wouldn't changing the pointer either always change the linked-list (and so P = P.next should modify L by getting rid of the first node), or never change the linked-list (and thus P.next = P.next.next should leave L unchanged)?
I have a feeling it has something to do with the fact that L.next is a pointer, just like P.next. So modifying P.next ends up modifying what L.next points to (?). But I feel like the rules aren't clear to me.