Saturday 10 February 2018

Inserting node at last position of list and print link list data in java

Inserting node at last position of list and print link list data,Inserting node at last position of list,how to Inserting node at last position of list,Inserting node at last position of list and print link list data in java

Add a node at the end

The new node is always added after the last node of the given Linked List. For example if the given Linked List is 50->100->105->220->250 and we add an item 330 at the end, then the Linked List becomes 50->100->105->220->250->330.


package com.dashzin.linklist;

public class AddAtEnd {
     Node head;
    
static class Node{
     int data;
     Node next;
     Node(int data){
          this.data=data;
          next=null;
     }
}

/* This method will prints data of linked list starting from head */
public void printList(){
     while(head!=null){
          System.out.print(head.data+" ");
          head=head.next;
     }
}

/* Inserts a new Node at the end of the list. */
public void atEnd(int new_data){
     Node new_node=new Node(new_data);
    
     /* check the list is empty or not, if list is empty then make new Node as head*/
     if(head==null){
          head=new_node;
          return;
     }
     /* Now new node is going to be the last node, so
    make next of it as null */
     new_node.next=null;
    
      /*traverse till the last node */
     Node last=head;
     while(last.next!=null){
          last=last.next;
     }
     /*Change the next of last node */
     last.next=new_node;
     return;
}

public static void main(String args[]){
     // creating four node for linklist
     AddAtEnd last=new AddAtEnd();
    
     last.head=new Node(10);
     Node first=new Node(2);
    
     //Link all the node with each other.....
    last.head.next=first;
    
    // calling method to add node at last position...
     last.atEnd(5);
     last.printList();
}
}


 If you are not getting how it has done then please just see the previous post of this topic... 





DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

0 comments:

Post a Comment