A Linked List is a linear data structure where elements are stored in nodes, and each node points to the next node in the sequence. Unlike arrays, linked lists can grow or shrink in size during execution.
Operation | Time Complexity |
---|---|
Access | O(n) |
Search | O(n) |
Insertion | O(1) |
Deletion | O(1) |
package main
import "fmt"
// Node structure
type Node struct {
data int
next *Node
}
// LinkedList structure
type LinkedList struct {
head *Node
}
// Insert at beginning
func (list *LinkedList) insertFront(data int) {
newNode := &Node{data: data}
newNode.next = list.head
list.head = newNode
}
// Print list
func (list *LinkedList) printList() {
current := list.head
for current != nil {
fmt.Printf("%d -> ", current.data)
current = current.next
}
fmt.Println("nil")
}
func main() {
list := LinkedList{}
// Insert elements
list.insertFront(3)
list.insertFront(2)
list.insertFront(1)
// Print list
fmt.Println("Linked List:")
list.printList()
}
public class LinkedList {
// Node class
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head;
// Insert at beginning
public void insertFront(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Print list
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
// Insert elements
list.insertFront(3);
list.insertFront(2);
list.insertFront(1);
// Print list
System.out.println("Linked List:");
list.printList();
}
}
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_front(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print_list(self):
current = self.head
while current:
print(f"{current.data} -> ", end="")
current = current.next
print("None")
# Example usage
if __name__ == "__main__":
# Create a linked list
llist = LinkedList()
# Insert elements
llist.insert_front(3)
llist.insert_front(2)
llist.insert_front(1)
# Print the linked list
print("Linked List:")
llist.print_list()
Insertion
Deletion
Traversal
Searching
Advantages:
Disadvantages:
Use linked lists when:
Avoid linked lists when:
Detecting Cycles
Reversing a Linked List
Finding Middle Element
Linked Lists are essential data structures that provide flexibility in managing dynamic data. Understanding linked lists is crucial for developing efficient algorithms and solving complex programming problems.