Linked List in Java - Full Implementation with Explanation
What is Linked List?
A linked list is a dynamic data structure with nodes containing data and a pointer to the next node. It allows
easy insertion and deletion without shifting elements like arrays.
Node Class
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
LinkedList Class with Insert, Display, Reverse, and Find Middle
class LinkedList {
Node head;
public void insertAtEnd(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;
}
}
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + ' ');
current = current.next;
}
}
public void reverse() {
Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
public void findMiddle() {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
if (slow != null) {
System.out.println('Middle element: ' + slow.data);
}
}
}
Main Class for Testing
public class Simple {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertAtEnd(3);
l.insertAtEnd(5);
l.insertAtBeginning(1);
l.display(); // prints: 1 3 5
l.reverse();
l.display(); // prints: 5 3 1
l.findMiddle(); // prints: Middle element: 3
}
}
Summary:
- Node class stores data and next pointer.
- LinkedList class manages insertion at beginning/end, display, reverse, and finding
middle.
- Practice these methods for linked list mastery in Java DSA.