Skip to main content

Linked List

SpaceTime
AccessLookupInsertionDeletion
O(n)O(n)O(n)O(1)O(1)

Definition​

Linked List is a dynamic data structure that consists of nodes, each containing data and a reference to the next node in the sequence.

Simplified

Linked List is like a treasure hunt game. You start at the 'head' node and follow links to other nodes, each holding data and a link to the next node. The last node, or 'tail', has no link. Just like the game, you traverse the list to find your 'treasure' or data.

Practice​

AspectPseudo Code
Prepend
prepend(data)
node = Node(data, head)
head = node
Insert Before
insert_before(value, data)
if head == ø:
return
if data.head == value:
node = Node(data, head)
head = node
return
current = head
while current.next != ø and current.next.data != value:
current = current.next
if current.next != ø:
current.next = Node(data, current.next)
Insert After
insert_after(value, data)
current = head
while current != ø and current.data != value:
current = current.next
if current != ø:
current.next = Node(data, current.next)
Insert at Index
insert_at(index, data)
if index < 0:
throw error "Index must be greater than or equal to 0"
if index == 0:
node = Node(data, head)
head = node
return
current = head
current_index = 0
while current != ø and index - 1 > current_index:
current = current.next
current_index++
if current == ø:
throw error "Index exceeds the size of the list"
current.next = Node(data, current.next)
Append
append(data)
if head == ø:
head = Node(data)
else:
current = head
while current.next != ø:
current = current.next
current.next = Node(data)
Find
find(value)
current = head
while current != ø and current.data != value:
current = current.next
return current.data
Delete Head
delete_head()
if head != ø:
head = head.next
Remove Node
delete(value)
if head == ø:
return
if head.data == value:
head = head.next
return
current = head
while current.next != ø and current.next.data != value:
current = current.next
if current.next != ø:
current.next = current.next.next
Delete Tail
delete_last()
if head == ø:
return
if head.next == ø:
head = ø
return
current = head
while current.next.next != ø:
current = current.next
current.next = ø
Reverse
reverse()
prev = ø
current = head
while current != ø:
next = current.next
current.next = prev
prev = current
current = next
head = prev
Traverse
traverse()
current = head
while current != ø:
yield current.data
current = current.next