Singly Linked List
A Singly Linked List is a linear data structure made up of nodes, where each node contains data and a reference (pointer) to the next node in the sequence. Unlike arrays, elements are not stored contiguously in memory.
Node Structure
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def delete(self, key):
current = self.head
prev = None
while current and current.data != key:
prev = current
current = current.next
if current is None:
return
if prev is None:
self.head = current.next
else:
prev.next = current.next
def traverse(self):
values = []
current = self.head
while current:
values.append(current.data)
current = current.next
return values
Complexity
| Operation | Time |
|---|---|
| Access by index | O(n) |
| Insert at head | O(1) |
| Insert at tail (no tail pointer) | O(n) |
| Delete | O(n) |
Advantages & Disadvantages
- Advantage: dynamic size, efficient insertions/deletions at the head.
- Disadvantage: no direct/random access; traversal is required to reach a given position, and extra memory is used for the next pointer.
Applications
- Implementing stacks and queues.
- Dynamic memory allocation systems.
- Building blocks for more advanced structures like hash maps (chaining) and graphs (adjacency lists).
Ready to master Data Structures & Algorithms?
Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.
.png)