1K
2 Likes

DSA Crash Course [Part 32] - Reverse List Approach

In this lesson, Alvin explores the strategy to solving the following interview problem:

Write a function, reverse_list, that takes in the head of a linked list as an argument. The function should reverse the order of the nodes in the linked list in-place and return the new head of the reversed linked list.

a = Node("a")
b = Node("b")
c = Node("c")
d = Node("d")
e = Node("e")
f = Node("f")
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f

# a -> b -> c -> d -> e -> f
reverse_list(a) # f -> e -> d -> c -> b -> a
x = Node("x")
y = Node("y")
x.next = y

# x -> y
reverse_list(x) # y -> x
p = Node("p")

# p
reverse_list(p) # p

If you need additional support taking these DSA skills and actually applying them, take Alvin's complete data structures and algorithms course on Structy. You can try out the concepts yourself in their interactive code editor and learn advanced DSA patterns like stack exhaustive recursion.

Use this link to get 20% off the entire Structy DSA learning experience.

Follow Alvin on LinkedIn: https://www.linkedin.com/in/alvin-zablan-b73a92117/