Basic structure and printing elements of Linked list in java


class Node{
     int data;
     Node next;
    
     Node(int data){
           this.data = data;
           this.next = null;
     }
}

public class LinkedList {
     Node head;
     public static void main(String[] args) {
           LinkedList list = new LinkedList();
           list.head = new Node(1);
           Node second = new Node(2);
           Node third = new Node(3);
          
           list.head.next = second;
           second.next = third;
          
           list.printList();
     }

      void printList() {
           Node node = head;
           //from start till last
           while (node!=null) {
                System.out.print(node.data);
                node = node.next;
                //to ignore last comma at last of list
                if(node!=null){
                     System.out.print(",");
                }
           }
     }

}                                                                   


Output-
1,2,3

No comments:

Post a Comment

Basic structure and printing elements of Linked list in java

class Node {      int data ;      Node next ;           Node ( int data ){            this . data = data ;            ...