Linked list creation and printing in java.

class Node {

    int val;

    Node next;

    Node(int val) {

        this.val=val;

    }

}

public class Main

{

    public static void Print(Node head){

        Node temp=head;

        while(temp!=null){

           System.out.println(temp.val);

           temp=temp.next;

       }

    }

    public static void PrintRecursive(Node head){

        if(head==null) return;

        System.out.println(head.val);

        PrintRecursive(head.next);

    }

public static void main(String[] args) {

   Node a = new Node(1);

   Node b = new Node(2);

   Node c = new Node(3); 

       Node d = new Node(4);

       Node e = new Node(5);

       a.next=b;

       b.next=c;

       c.next=d;

       d.next=e;

       Print(a);

       // print elements by recursion 

       PrintRecursive(a);

}

}

output ->

1

2

3

4

5

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.