Reverse Linked List
L6 Medium Linked List
Concept
Linked lists are connected by their
next pointers. Reversing one is simply flipping each pointer to point backward as you walk it.Given the head of a singly linked list whose nodes hold integers, reverse the list in place and return the new head.
Examples
▸ head = [1, 2, 3, 4, 5]
→ [5, 4, 3, 2, 1]
▸ head = [1, 2]
→ [2, 1]
▸ head = []
→ []
Progressive Hints
Hint 1 · Nudge
Slide three pointers so each node points backwards, one node at a time.
Hint 2 · Plan
Keep a previous and a current node. Each step: save current's next, point current's next at previous, then move previous and current forward. Previous ends up as the new head.
Hint 3 · Approach
prev = nil, cur = head. While cur: save nxt = cur.next; cur.next = prev; prev = cur; cur = nxt. Return prev.
All hints are out. Take a breath and give it a shot.
Output
// Run your code to see the output here.