Given an integer n denoting number of elements in linked list. And then we are given n integers where the ith integer denoted ith element of linked list we need to print the linked list in reverse i.e from tail to head
Input
The First line of input contains a single integer n denoting size of linked list The Second line contains n integers where ith integer denotes ith element of linked list
Output
Ouput linked list in reverse order i.e from last node(tail) to head node
Constraints:
1 <= n <= 10^3
Sample Input:
5 2 6 8 10 1
Sample Output:
1 10 8 6 2
Solution:–
import java.util.*; import java.lang.*; import java.io.*; class Node { int data; Node next; Node(int data) { this.data=data; this.next=null; } } public class Main { static Node head=null; static void insertAtHead(int data) { Node newNode=new Node(data); if(head==null) { head=newNode; return; } newNode.next=head; head=newNode; } static void printlist() { Node currnode=head; while(currnode!=null) { System.out.print(currnode.data+" "); currnode=currnode.next; } } public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc=new Scanner(System.in); int n=sc.nextInt(); for(int i=0;i<n;i++) { int data=sc.nextInt(); insertAtHead(data); } printlist(); } }
Add a Comment