☰ All problems

3. Reverse Linked List

EasyLinked ListRecursion

Given the head of a singly linked list, reverse the list and return the new head.

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 is in the range [0, 5000]
  • -5000 <= Node.val <= 5000
💡 Hint 1

Walk the list once, flipping each next pointer to point backwards.

💡 Hint 2

You need three references: previous, current and the saved next node.

/**
 * Definition for singly-linked list (provided):
 * function ListNode(val, next) { this.val = val ?? 0; this.next = next ?? null; }
 *
 * @param {ListNode} head
 * @return {ListNode}
 */
function reverseList(head) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc