206. Reverse Linked List
Linked Lists are linear data structures which are pointing in either one or two directions (doubly LLs). Looking at the name, they are linked - but linked to what? Well the elements in a list (let’s call each a node
). The node are connected to each other (hence link), in the sense that they are pointing to one another. So, each node has to have a next
pointer, and a value
variable. Consider this Java class for a Node of a LL.
To reverse a linked list, we need four important steps including traversing the list. For every node, we are
- storing the direct next variable temporarily (
next = current.next
). - updating the next of the current node to the previous. This is where the “reversing” happens. (
current.next = prev
) (Rememberprev
would be initiallynull
, which is correct because the previous of thehead
will be anull
pointer.) - update the
prev
pointer to thecurrent
one. Think from the perspective of the while loop which is iterating the list, thecurrent
pointer is the one we are on. Because we are reversing, we have to set thecurrent
as theprevious
. Just like if we were building a linked list from an array, we would setcurrent
tocurrent.next
. (prev = current
) - and lastly, we update the current to next. (
current = next
).
Code:
Java
— A