A linked list is a linear data structure where each element (a "node") points to the next one, instead of sitting in contiguous memory like a list/array. Interviewers ask about it constantly because it tests whether you understand pointers/references, and because many classic problems (cycle detection, reversing a list, merging two sorted lists) are built on top of it.
Python doesn't have a built-in linked list type, so this post implements one from scratch with a Node class and a LinkedList class supporting append, prepend, and delete.
Python Program to Implement a Singly Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete(self, value):
current = self.head
previous = None
while current:
if current.data == value:
if previous is None:
self.head = current.next
else:
previous.next = current.next
return True
previous = current
current = current.next
return False
def to_list(self):
result = []
current = self.head
while current:
result.append(current.data)
current = current.next
return result
# Demo
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.append(30)
ll.prepend(5)
print("List:", ll.to_list())
ll.delete(20)
print("After deleting 20:", ll.to_list())
Output:
List: [5, 10, 20, 30]
After deleting 20: [5, 10, 30]
append and delete both walk the list iterating over a list of nodes, which is O(n) — the trade-off for not needing contiguous memory like a Python list, and for O(1) insertion at the front with prepend. A common follow-up interview question is reversing this list in place, or implementing a doubly linked list where each node also tracks its previous node for O(1) backward traversal.
