✅ 1. Singly Linear Linked List - Delete Position
class Node {
int data;
Node next;
Node(int data) { this.data = data; }
}
class SinglyLinkedList {
Node head;
void deleteAtPosition(int pos) {
if (head == null || pos <= 0) return;
if (pos == 1) {
head = head.next;
return;
}
Node temp = head;
for (int i = 1; i < pos - 1 && temp != null; i++)
temp = temp.next;
if (temp == null || temp.next == null) return;
temp.next = temp.next.next;
}
}
✅ 2. Doubly Linear Linked List Operations
class DNode {
int data;
DNode prev, next;
DNode(int data) { this.data = data; }
}
class DoublyLinkedList {
DNode head, tail;
void addFirst(int val) {
DNode newNode = new DNode(val);
if (head == null) {
head = tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
void addLast(int val) {
DNode newNode = new DNode(val);
if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
void deleteFirst() {
if (head == null) return;
head = head.next;
if (head != null) head.prev = null;
else tail = null;
}
void deleteLast() {
if (tail == null) return;
tail = tail.prev;
if (tail != null) tail.next = null;
else head = null;
}
void displayForward() {
DNode temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
void displayBackward() {
DNode temp = tail;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.prev;
}
}
}
✅ 3. Linked List Algorithms
a) Display in Reverse (Recursion)
void displayReverse(Node head) {
if (head == null) return;
displayReverse(head.next);
System.out.print(head.data + " ");
}
b) Reverse Entire List
Node reverse(Node head) {
Node prev = null, curr = head, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
c) Find Middle Node
Node findMiddle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
d) Detect Cycle (Floyd’s)
boolean hasCycle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
e) Palindrome Check
boolean isPalindrome(Node head) {
Stack<Integer> stack = new Stack<>();
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) slow = slow.next;
while (slow != null) {
if (stack.pop() != slow.data) return false;
slow = slow.next;
}
return true;
}
✅ 4. Data Structure Applications Using Linked List
Stack