A linked list is a linear data structure where elements are stored in nodes. Each node contains a data field and a reference (or link) to the next node in the sequence.
Basic Structure
[Data|Next] -> [Data|Next] -> [Data|Next] -> null
Types of Linked Lists
Singly Linked List
Doubly Linked List
Circular Linked List
1. Singly Linked List
In a singly linked list, each node points to the next node in the sequence. In the following examples, the dot (•) is a pointer to the relevant node:
Example:
[3|•] -> [7|•] -> [1|•] -> [9|•] -> [4|•] -> null
Operations: - Access: O(n) - Search: O(n) - Insertion at beginning: O(1) - Insertion at end: O(n) - Deletion at beginning: O(1) - Deletion at end: O(n)
Example:
class Node:def__init__(self, data):self.data = dataself.next=Noneclass SinglyLinkedList:def__init__(self):self.head =Nonedef append(self, data): new_node = Node(data)ifnotself.head:self.head = new_nodereturn last =self.headwhile last.next: last = last.next last.next= new_nodedef__str__(self):ifnotself.head:return"empty" current =self.head result = []while current: result.append(f"[{current.data}|•]") current = current.next result.append("null")return" -> ".join(result)sll = SinglyLinkedList()sll.append(3)sll.append(7)sll.append(1)sll.append(9)sll.append(4)print("Singly Linked List:", sll)