Reverse a singly linked list.
Tags
LinkedList
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Trying to find the rules by sketching the flow of reverse LinkedList A => B => C => D => E
So we have the following
null <= A => B => C => D => E
null <= A <= B => C => D => E
null <= A <= B <= C => D => E
null <= A <= B <= C <= D => E
null <= A <= B <= C <= D <= E
For each round, we will reverse one next pointer to its previous
So we have the rules for each node:
var next = node.next;
node.next = prev;
prev = node;
node = next;
Then we have the following code:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
if (head === null) {
return head;
}
var prev = null;
var node = head;
while (node.next !== null) {
var next = node.next;
node.next = prev;
prev = node;
node = next;
}
node.next = prev;
return node;
};