Page 530 - Computer science 868 Class 12
P. 530

4.   Write an algorithm/Java code to insert a node at the middle of an existing linked list using method: void
                    insertMid(Node start, int item, nt pos) where start refers to the start pointer and item is the data value and
                    pos is the position where it will be inserted.

                                    start 1001



                                      29      1098               18      1156   2145             35       NULL
                                          1001                         1098                          1156


                                                                               45       1156
                                                                                  ptr 2145
               Ans.  Algorithm
                    Step 1:  Start.

                    Step 2:  Create new Nodes ptr and temp
                    Step 3:  Assign ptr.data=item and ptr.next=null

                    Step 4:  Assign temp=start
                    Step 5:  Initialise c to 1
                    Step 6:  Repeat Step 7 to Step 8 while c<pos-1

                    Step 7:  Assign temp = temp.next
                    Step 8:  Increase c by 1

                    Step 9:  Assign ptr.next= temp.next
                    Step 10: Set temp.next= ptr
                    Step 11: Stop.

                    Java Code

                    void insertmid(Node st, int item, int pos)
                    {
                    Node ptr=new Node();
                    ptr.data=item; // initialise data to item and next to null
                    ptr.next=null
                    Node temp=start;
                    int c=1;
                    while(c<pos) // move pointer to the given position
                    {
                    c++;
                    temp=temp.next;
                    }
                    ptr.next=temp.next;
                    temp.next=ptr;
                    }







                528528  Touchpad Computer Science-XII
   525   526   527   528   529   530   531   532   533   534   535