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 end of the list
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = 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.addLast(data);
}
System.out.println("The linked list is: ");
list.display();
}
}
Enter the number of nodes: 5
Enter the data for node 1: 7
Enter the data for node 2: 5
Enter the data for node 3: 4
Enter the data for node 4: 6
Enter the data for node 5: 9
The linked list is:
7 5 4 6 9
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 end of the list, and a method to display the list.addLast
method, a new node is created with the specified data. If the list is empty (i.e. the head is null
), the new node becomes the head of the list. Otherwise, the method traverses the list starting from the head, and finds the last node. The next
field of the last node is set to the new node, making it the new last node.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 addLast
method to add it to the end of the list. Finally, the program calls the display
method to display the list.