Algorithm to insert node in Simple Linked List

Insert_LinkedList ( List, Node, Start, Value,Data)

In this algorithm List is a linked list having n nodes. Start is a pointer which contains the address of starting node of the list.Node  is the pointer pointing to the new node. Value is the data of a node from list after which the new node is to be inserted.Data is the value which is to be assigned to the data part of new node.
Node->data contains data and Node->Next points next node. In this algorithm following criteria are followed.
  • If List is empty Node will be inserted at starting of list
  • If Value found in the list than node will be inserted after the value
  • else node will be inserted at the end of list

Ptr is an intermediate pointer which points the current node and used to traverse the list

Step 1: i) Node ->data = Data
Step 2: [Check if list is empty then we will insert new node at the starting point.]
            If Start = null then go to step 3 else go to step 4

Step 3: i) Node->Next=null.
            ii) Start=Node
            iii) Return

Step 4: [assigning the 1st node address to Ptr]
                  Ptr = Start

Step 5: While Ptr->Next is Not null repeat
            i) if Ptr->data = Data then go to step i.a else go to step ii)
                     a) Node->Next = Ptr->Next
                     b) Ptr->Next = Node
                     c) Return
           ii) Ptr = Ptr->Next
Step 6: [If Value that was searched not found, in that case inserting Node at the end of List]
            i)Node->Next = null
           ii)Ptr->Next = Node

Step 7: End



Click here for Explanation


No comments:

Post a Comment