Reverse Linked List
Problem
Given the head
of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2] Output: [2,1]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
Solution
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let prev = null;
let cur = head;
while (cur) {
[cur.next, cur, prev] = [prev, cur.next, cur];
}
return prev;
};
Keep track of the previous node prev
and the current node cur
while reversing the list iteratively.
Follow-up
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head, prev = null) {
if (!head) {
return prev;
}
const next = head.next;
head.next = prev;
return reverseList(next, head);
};
Reverse each node recursively and return the new head (ie. old tail) at the end.