import java.util.LinkedList;
import java.util.Scanner;
class Node
{
int data;
Node next;
Node(int data, Node next)
{
this.data = data;
this.next = next;
}
}
public class Main
{
public static void printList(Node head)
{
Node ptr = head;
while (ptr != null)
{
System.out.print(ptr.data + " ");
ptr = ptr.next;
}
}
public static Node reverse(Node head)
{
Node previous = null;
Node current = head;
while (current != null)
{
Node next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.print("Input the number of nodes: ");
int size = sc.nextInt();
System.out.print("Please input data for node: ");
int keys[] = new int[size];
for(int i = 0; i < size; i++)
{
keys[i] = sc.nextInt();
}
Node head = null;
for (int i = size - 1; i >= 0; i--)
{
head = new Node(keys[i], head);
}
head = reverse(head);
printList(head);
}
}
What I have tried:
I think im not using the linked list
and I want to save a user input into the linked list
like if he inputs 3 nodes
then he will input a number to
node 1 = 5
node 2 = 6
node 3 = 7
and the output will be a reverse which i already done in my code
I just want it to print out like this
Input the number of nodes : 3
Input data for node 1 : 5
Input data for node 2 : 6
Input data for node 3 : 7
Data entered in the list are : 5 6 7
The list in reverse are : 7 6 5