Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Linked lists, trees and graphs

Linked list

A linked list is a data structure that consists of nodes, where each node has a value and a link to the next node.

Compared to arrays, the elements are not necessarily stored contiguously. That means inserting or deleting an element does not require moving other elements, but you cannot access an element by index in constant time.

1→2→3→∅

Time complexity

operationtime
insert after a known nodeO(1)O(1)
delete after a known nodeO(1)O(1)
search for a valueO(n)O(n)

Implementation

Search for a value

Given the head of a linked list and a value, check if the value is in the list.

Start at the head and follow next until the value is found or the pointer is empty. In the worst case every node is visited once, so it takes O(n)O(n) time.

1node → 2 → 3 → ∅
1 is not 3, move to 2
1 / 3

Insert a node

Given a node of a linked list, insert a new node with a given value right after the given node.

Create the new node pointing to the node after the given one, then point the given node to the new node. Only two pointers change and nothing else in the list moves, so it takes O(1)O(1) time.

1 → 2node → 4
create 3 and point it to 4
1 / 3

Delete a node

Given a node of a linked list, delete the node right after it.

Point the given node to the node after the next one. Only one pointer changes and nothing else in the list moves, so it takes O(1)O(1) time.

1 → 2node → 3 → 4
point 2 to 4
1 / 2

Build it

Implement contains, insert_after and delete_after in the class below. For the insert and delete we have to find the node first, so the time complexity will be O(n).

Build a linked list
Python
# Definitions:
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class LinkedList:
def __init__(self, values: list[int]) -> None:
self.head = None
for value in reversed(values):
self.head = ListNode(value, self.head)
def contains(self, val: int) -> bool:
# Return True when val is in the list
return False
def insert_after(self, target: int, val: int) -> None:
# Insert a new node holding val right after the node holding target
pass
def delete_after(self, target: int) -> None:
# Delete the node right after the node holding target
pass
def print(self) -> None:
values = []
node = self.head
while node:
values.append(str(node.val))
node = node.next
print(" -> ".join(values))
linkedList = LinkedList([1, 2, 4])
linkedList.insert_after(2, 3)
print(linkedList.contains(3), linkedList.contains(9))
linkedList.delete_after(2)
linkedList.print()
Was this lesson helpful?