Inserting Node in Two Way Linked List

As we all know, in Two-Way linked list there are two Pointer's fields, with a data Field. One Pointer Field is known as Previous Pointer, which points Previous Node. Previous Pointer will be null, if it is First Node. Another Pointer Field is known as Next Pointer, which points to the next node. Next Pointer will be null if it is last node. There are Two External pointer called Start & End. Start pointer points Starting node of the list, End pointer points the last pointer of the List.
                   

Insert_Node_2wayList(List,DataAfter,Start,End,NewNode)


Here List is a 2 way linked list containing n Nodes. Start, End are the starting and Ending pointers pointing to the First and Last Node of the List. DataAfter is a value in a Node after which the NewNode will have to be inserted. 
Ptr is an intermediate pointer which will be used to traverse the list
Conventions: <> = Not Equals to
Step 1: [checking, if List is empty]
            if Start=null then
                   NewNode->Prev = null
                   NewNode->Next = null
                   Start = NewNode
                   End = NewNode
                   return Success;
Step 2:[Initializing the pointer]
           Ptr = Start
Step 3: [List is Not Empty Now Searching for the Node after which new Node is to be inserted. After this loop Ptr pointer of the node after which new node is to be inserted or null if the node not found]
            While Ptr <> null and Ptr->Data <> DataAfter repeat the step
                          i) Ptr=Ptr->Next

Step 4: [Check, if the Node found or not]
            if Ptr = null then
                 return Failure;

Step 5: [Inserting node]
             NewNode->Prev = Ptr              [New Node's Previous pointer will point current Node]
             NewNode->Next = Ptr->Next  [New Node's Next pointer will point Next Node current Node]
             Ptr->Next->Prev = NewNode  [Next Node of current node will point new node]
             Ptr->Next = NewNode              [Next of Current Node will point new node]

Step 6: return Success;

No comments:

Post a Comment