Let’s try to understand what the above code does:
Now let’s see how the same linked list can be used as a stack with slight modifications in node insertion technique. Below is the code:
Stack resembles LIFO (last in first out) and thus, every time a new node is added to the beginning of the list as shown in the code above.push() adds an item to the stack top and pop() returns the top element from the stack.
Let’s move a bit further and try to implement a doubly linked list as well. Below is the code:
Doubly linked list has two links within a node viz. left and right links. right link points to the node on the right of current node and the right node of current one is linked back to the previous neighbour using leftLink. This, is exactly what the above code is doing.All implementation is similar to that of singly linked list except each node having bidirectional links.