JAVA-3
ASSIGNMENT
Q.3 Write a java program to. create and display Singly linked list and perform following task.
Insert node at specific position.
Delete node from specific position.
Solution :-Â
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
private Node head;
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
public void insertAtPosition(int data, int position) {
Node newNode = new Node(data);
if (position == 0) {
newNode.next = head;
head = newNode;
return;
}
Node temp = head;
for (int i = 0; temp != null && i < position - 1; i++) {
temp = temp.next;
}
if (temp == null) {
System.out.println("Position out of range");
return;
}
newNode.next = temp.next;
temp.next = newNode;
}
public void deleteAtPosition(int position) {
if (head == null) {
System.out.println("List is empty");
return;
}
if (position == 0) {
head = head.next;
return;
}
Node temp = head;
for (int i = 0; temp != null && i < position - 1; i++) {
temp = temp.next;
}
if (temp == null || temp.next == null) {
System.out.println("Position out of range");
return;
}
temp.next = temp.next.next;
}
}
public class LinkedListDemo {
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n1. Insert at position\n2. Delete from position\n3. Display\n4. Exit");
System.out.print("Enter choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data: ");
int data = scanner.nextInt();
System.out.print("Enter position: ");
int pos = scanner.nextInt();
list.insertAtPosition(data, pos);
break;
case 2:
System.out.print("Enter position to delete: ");
pos = scanner.nextInt();
list.deleteAtPosition(pos);
break;
case 3:
list.display();
break;
case 4:
scanner.close();
return;
default:
System.out.println("Invalid choice");
}
}
}
}
Output :-