DSA AnimatorREVISION VIDEOS
← Back to problems
New

Reverse Linked List — LeetCode 206 video explanation

Given the head of a singly linked list, reverse the list. Return the new head.

Loading videos…

DSA Animator › DSA Revision › Linked List › Reverse Linked List

Key moments in the Reverse Linked List video

0:04Problem0:08Example0:13Brute force0:21Key idea0:31Dry run0:45Code0:58Takeaway

What you will learn

Remember: save next, flip the arrow, then step forward. Previous ends up as the new head. The video solves Reverse Linked List (LeetCode 206, Easy) with the Pointer Reversal pattern from the Linked List topic, and you can replay every step in the interactive Reverse Linked List animation.

Reverse Linked List video transcript

Problem

Given the head of a singly linked list, reverse the list. Return the new head.

Example

For 1, 2, 3, 4, 5, the result is 5, 4, 3, 2, 1.

Brute force

Pushing every value onto a stack and rebuilding uses O of n extra space. We can just flip the arrows in place.

Key idea

Keep three pointers: previous, current and next. Save next, then point current back at previous. Move previous and current one step forward, and repeat until current is null.

Dry run

Previous starts at null, and current at 1. Point 1 back to null, then move on to 2. Point 2 back to 1, then 3 back to 2. Then 4 back to 3, and 5 back to 4. Current is null, so previous, at 5, is the new head.

Code

In code, start with previous as null and current as head. In the loop, save next, set current dot next to previous, then shift both pointers. Return previous, so it's O of n time and O of 1 space.

Takeaway

Remember: save next, flip the arrow, then step forward. Previous ends up as the new head.

More Linked List revision videos

← All 185 DSA revision videos