E
E
Egor Babintsev2021-01-15 20:02:48
Data Structures
Egor Babintsev, 2021-01-15 20:02:48

How does assignment to tail of a linked list work?

Sandbox link: https://codesandbox.io/s/youthful-noether-2wekf?fi...

Good afternoon. I started learning data structures, I started with a linked list. There was a question about the append method. On lines 16 and 17 there is an assignment that I do not understand. Why do we need to update tail's next property if we overwrite it on the next line? So also for some reason, in some magical way, if you look through the debugger at this moment, newNode is also assigned to the next property, inside the head, which does not appear here at all. And if you also display the value of this.head at the beginning of the append method, then at the first call it will be null (logically), and already at the second call it will contain LinkedNodeList in the same form as at the third iteration (that is, inside it there will be a chain out of 3 nested nodes, even though the function is called only the second time) How does this happen? Thank you in advance for the explanation, otherwise I'm kind of shocked

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-01-15
@egor_babintsev

head, tail and next here are links not elements in the list, pointers or whatever it is called in typescript. These variables do not store the LinkedListNode, but only point to such an element somewhere in memory. The first operation this.tail.next = newNode;makes the last element in the list refer to the new element we add to the end. Just updating the link at the last element.
The following operation moves the tail link to point to the new element just added.
At the very beginning, when you add the second element, head and tail will point to the same vertex. So changing tail.next changes head.next at the same time, because head and tail both point to the same place.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question