Mark As Completed Discussion

Example 1: Reversing a linked list

Order in a singly linked list is determined by a node's next property. The next pointer can refer to another node or it can point to null.

Reversing a linked list means reassigning all the next properties on every node. So we are going from this:

Example 1 Reversing A Linked List

To this:

Example 1 Reversing A Linked List

There are many ways to reverse a linked list however the way I will demonstrate a simple way using 3 pointers. The idea is to use the three pointers: next, current, and prev.

In the reverse(Node head) method, the current is the main pointer running down the list. The next pointer leads it and the prev pointer trails it. In each iteration, the current pointer is reversed and then advance all three to get the next node.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment