Skip to main content
All tracks
DSA in Python

Linked Lists

A linked list stores values in nodes; each node points to the next one. There is no random access, but insertion and deletion at a known node are O(1).

class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next


def from_list(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head


def to_list(head):
out = []
while head:
out.append(head.value)
head = head.next
return out

Reverse a list​

def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev

Detect a cycle (Floyd)​

def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False # O(n) time, O(1) space

Find the middle​

Move fast two steps for every one step of slow; when fast reaches the end, slow is at the middle.

Finished reading?

Mark it complete to track your progress across the docs.

Questions and discussion

Stuck on something here, or found a clearer way to explain it? Start a thread.

All discussions
  • Ask a question or share what helped
  • React to useful answers
  • Sign in with GitHub to post

Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.