Python Data Structures - Linked List - Part 2


 Let's see how to insert a node into a singly linked list diagrammatically:


Here is my singly linked list with 2 nodes.

The Linked list starts with HEAD -> Hold the address of the next node -> 001 -> Address of node1 -> Node1 holds the address of Node2 -> Node2 is the last node in the linked list and it has NULL reference.



Now, Let's insert a node called "Node3" at the beginning of the linked list.

So, When we add a node at the beginning of the list:

1) Make sure the HEAD is updated to point at the new node address (003).
2) New node holds the reference to the previous HEAD node (001).

HEAD (003) -> Node 3 refers to 001 -> Node 1 refers to 002 -> Node 2 is NULL.

What happens when the node is added to the end of the list:

Let's add Node 4 to the end of the list:


This is going to be straightforward. Update the previous last node pointing to the address of the new node (004) and the new node pointing to NULL as it is the last node of the list.







Comments

Popular posts from this blog

SRE/DevOps Syllabus

AWS Code Commit - CI/CD Series Part 1

Docker - Preventing IP overlapping