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 add(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 insert a node at the middle of the list
public void insertMiddle(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node slow = head;
Node fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node newNode = new Node(data);
newNode.next = slow.next;
slow.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.add(data);
}
System.out.println("The linked list is: ");
list.display();
System.out.print("\nEnter the data for the new node: ");
int data = input.nextInt();
list.insertMiddle(data);
System.out.println("The linked list after inserting the new node is: ");
list.display();
}
}
Enter the number of nodes: 5
Enter the data for node 1: 8
Enter the data for node 2: 7
Enter the data for node 3: 2
Enter the data for node 4: 5
Enter the data for node 5: 13
The linked list is:
8 7 2 5 13
Enter the data for the new node: 3
The linked list after inserting the new node is:
8 7 2 3 5 13
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, methods to add nodes to the end of the list, insert a node at the middle of the list, and display the list.add
method, a new node is created with the specified data, and added to the end of the list. If the list is empty, the new node becomes the head. If the list is not empty, the method traverses the list until it reaches the last node, and adds the new node as its next node.insertMiddle
method, the method checks if the list is empty. If the list is empty, the method creates a new node with the specified data and sets it as the head of the list. If the list is not empty, the method uses two pointers, slow
and fast
, to traverse the list. slow
moves one node at a time, while fast
moves two nodes at a time. When fast
reaches the end of the list, slow
is at the middle of the list. The method then creates a new node with the specified data, and inserts it after slow
.