Page 529 - Computer science 868 Class 12
P. 529

Step 4:  Assign ptr.next=start
                      Step 5:  Set start=ptr

                      Step 6:  Stop.
                       Java Code

                      void insertBegin(Node start , int item)
                      {
                      Node ptr=new Node(); // creating a new node ptr
                      ptr.data=item;           // initialising the data
                      ptr.next=start;     // linking the address of the node which was previously the first node
                      start=ptr;              // changing the address of the start pointer
                      }
                   3.   Write  an  algorithm/Java  code  to  insert  a  node  at  the  end  of  an  existing  linked  list  using  method:  void
                      insertEnd(Node start, int item)  where start refers to the start pointer and item is the data value.

                                      start 1001




                                         29      1098               18      1156               35     NULL 2145
                                            1001                       1098                        1156

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

                      Step 2:  Create new Nodes ptr and ptr1
                      Step 3:  Assign ptr.data=item
                      Step 4:  Assign ptr1=start

                      Step 5:  Repeat Step 6 while ptr1.next!=null
                      Step 6:  Assign ptr1 = ptr1.next

                      Step 7:  Assign ptr1.next=ptr
                      Step 8:  Set ptr.next=null
                      Step 9:   Stop.

                      Java Code
                      void insertEnd(Node start ,int item)
                      {
                      Node ptr=new Node();
                      ptr.data=item;
                      Node ptr1=start;
                      while(ptr1.next!=null) // traversing to the last node of the linked list
                      { ptr1=ptr1.next; }
                      ptr1.next=ptr;   // Joining the linked list with the new node
                      ptr.next=null;  //  Address of the last node initialize to null
                      }



                                                                                                                       527
                                                                                                       Data Structures  527
   524   525   526   527   528   529   530   531   532   533   534