Linked List | (Inserting a node) - cook the code

Sunday, 14 January 2018

Linked List | (Inserting a node)

Linked List | (Inserting a node):-
In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.

Add a node at the front: (A 4 steps process)
The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this)
linkedlist_insert_at_start
Following are the 4 steps to add node at the front.

Time complexity of push() is O(1) as it does constant amount of work.
Add a node after a given node: (5 steps process)
We are given pointer to a node, and the new node is inserted after the given node.
linkedlist_insert_middle
Time complexity of insertAfter() is O(1) as it does constant amount of work.


Add a node at the end: (6 steps process)
The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30.
Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.
linkedlist_insert_last
Following are the 6 steps to add node at the end.
Time complexity of append is O(n) where n is the number of nodes in linked list. Since there is a loop from head to end, the function does O(n) work.
This method can also be optimized to work in O(1) by keeping an extra pointer to tail of linked list

Following is a complete program that uses all of the above methods to create a linked list.

Output:
 Created Linked list is:  1  7  8  6  4

No comments:

Post a Comment