import java.util.Scanner;
public class SinglyLinkedList {
// Node class
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Head of the linked list
Node head;
// Method to add a node to the beginning of the list
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Method to display the list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SinglyLinkedList list = new SinglyLinkedList();
System.out.print("Enter the number of nodes: ");
int n = input.nextInt();
for (int i = 1; i <= n; i++) {
System.out.print("Enter the data for node " + i + ": ");
int data = input.nextInt();
list.addFirst(data);
}
System.out.println("The linked list is: ");
list.display();
}
}
Enter the number of nodes: 5
Enter the data for node 1: 15
Enter the data for node 2: 21
Enter the data for node 3: 29
Enter the data for node 4: 37
Enter the data for node 5: 45
The linked list is:
45 37 29 21 15
Node
class to represent a node in the linked list. Each node contains an integer data
and a reference to the next node in the list. The SinglyLinkedList
class contains a reference to the head of the list, a method to add a node to the beginning of the list, and a method to display the list.addFirst
method, a new node is created with the specified data, and added to the beginning of the list. The next
field of the new node is set to the current head of the list, and the new node becomes the new head of the list.display
method, the method traverses the list starting from the head, and prints the data of each node.main
method, the program creates a new SinglyLinkedList
object, prompts the user to enter the number of nodes, and then prompts the user to enter the data for each node. For each node, the program calls the addFirst
method to add it to the beginning of the list. Finally, the program calls the display
method to display the list.