Studying singly linked lists and need help understanding pointer functionality
I would love some help understanding something in the following leetcode problem Merge Two Sorted Lists:
When debugging the solution, I can see that during the while loop that setting the pointer
current.next = temp
modifies dummy.next
to equal the temp
ListNode. However, setting the pointer current = current.next
does not modify dummy. Why is that?12 Replies
well, why would it?
you're making the
current
variable reference a different object, not changing any object itselfI guess what is breaking my brain is the following:
- I set current = dummy (current is now the object dummy instead of just a copy)
- I set current.next = temp (dummy.next now equals temp and so does current.next)
- I set current = temp (why does temp not replace dummy as a whole since setting current.next changes dummy.next?)
when you have current = dummy you have 2 pointers in the stack that point to the same memory in the heap.
that next property is stored in that same memory in the heap
thats why you can alter it with current and dummy itself
I think I am following. I am guessing that
current
and dummy
are stored in different memory and that's why changing one does not overwrite the other. With dummy
being initialized to a val = 0
from the ListNode constructor, why does dummy not keep that val when creating the chained nodes?current and dummy are just pointers with the same value(address)
when you change current to other node you just change its value(address)
not the data behind that address
What documentation can I look up to learn more about this? When doing searches around variables, pass-by-value, pointers, addresses, I get thrown a lot of info about pointers in the literal sense like
int* ptr
.the best way to learn about them is by working with them in c/c++
So I guess the following would be true if my understanding is correct:
Basically, if I change the new object that references the previous object to a new object or null, only the new object changes.
However, in the original code block, during the while loop,
current.Next
still updates the links between the nodes. Is this because the property is the same as the object?next property is inside that allocated memory in the heap, so current.Next and dummy.Next are working with the same object(pointer to the object)
Car
and ListNode
are objects and go on the heap, including their properties. The local variables myCar
, newCar
, dummy
, and current
are on the stack. When I code current.next
or myCar.IsRunning
, I am referring to the heap object and not the local variable?
aka:
yes
Thanks. Everytime I have come across pass by reference or pass by value or stack vs heap, I feel like a novice all over again. It's like one hurdle I never conquered.