After studying linked lists, this very popular question pops up: How do you reverse a linked list? Not just that, but how do you do it in place? The first time I reviewed this question, I had a hard time wrapping my head around it, but it finally clicked!

Let’s get started.


Singly Linked List Review

If you’re not familiar with the basics of a singly linked list, check out my previous article.

The foundation of our singly linked list can be seen on GitHub.


Overview

Our linked list example will be 1 → 2 → 3 → 4.

The result we’re looking for is 1 ← 2 ←3 ←4.

The key thing to remember about a singly linked list is that each node only contains its value and a pointer to the next node. There is _no _pointer to the previous node. So, we’ll have to keep a variable that holds the reference to the previous node. We’ll also have to keep a variable that holds the reference to the next node.

I’m sure you’re wondering why since each node has a next pointer. As we loop through the list and change the current node’s next pointer value, we lose our next pointer in the iteration. As a result, we’ll have to keep track of the next node to know where we’re going.

Our method will be starting at the beginning of the list and changing the direction of the pointers as we move along the list.

Graphic displaying linked list of 1 > 2 > 3> 4, with head set at 1, and tail at 4. Current node is 1.

Our singly linked list example.

#javascript #linked-lists #software-engineering #data-structures

Reverse Reverse!... A Linked List?
1.35 GEEK