5 Linked List
5 Linked List
Table of Contents
A Linked List is a linear data structure where each element (node) contains data and
a reference (or link) to the next node in the sequence.
Types of Linked Lists:
o Singly Linked List
o Doubly Linked List
o Circular Linked List
Node Structure:
o Data: Holds the actual data.
o Next Pointer (Singly Linked List): Points to the next node in the sequence.
o Prev Pointer (Doubly Linked List): Points to the previous node.
Each node in a linked list is dynamically allocated and connected using pointers.
list.traverse(); // Output: 1 2 3
}
}
class LinkedList {
Node head; // Head node of the linked list
list.traverse(); // Output: 1 2 3 4
}
}
Using java.util.LinkedList with import java.util.*;
import java.util.*; // Import the java.util package
public class Main {
public static void main(String[] args) {
// Create a new LinkedList using java.util.LinkedList
LinkedList<Integer> list = new LinkedList<>();
class LinkedList {
Node head; // Head node of the linked list
if (head.next == null) {
head = null; // If only one element, delete the head
} else {
Node current = head;
while (current.next != null && current.next.next != null) {
current = current.next; // Traverse to the second-last
node
}
current.next = null; // Remove the last node
}
}
list.deleteAtBeginning(); // Deletes 3
list.deleteAtEnd(); // Deletes 1
list.traverse(); // Output: 2
}
}
Here's the rewritten code using java.util.LinkedList:
import java.util.*; // Import java.util package
class DoublyLinkedList {
DoublyNode head;
list.head = node1;
node1.next = node2;
node2.prev = node1;
node2.next = node3;
node3.prev = node2;
list.traverseForward(); // Output: 1 2 3
list.traverseBackward(); // Output: 3 2 1
}
}
class CircularNode {
int data;
CircularNode next;
class CircularLinkedList {
CircularNode head;
list.head = node1;
node1.next = node2;
node2.next = node3;
node3.next = node1; // Circular link
list.traverse(); // Output: 1 2 3
}
}
Dynamic Memory Allocation: Efficient memory usage for dynamic data structures.
Implementing Stacks and Queues: Linked lists provide dynamic sizing.
Circular Linked Lists: Real-time systems and buffer management.
Conclusion
Linked lists are fundamental data structures used in a wide range of applications. They are
especially useful in dynamic memory management, and their flexibility makes them ideal for
tasks where elements are frequently added or removed.