Reverse Linked List Easy 0 attempts
LeetCode ↗

Reverse Linked List

Easy Linked List LeetCode

You get the head of a singly linked list. Reverse the links so the former last node becomes the head. Return the new head.

Do it by changing next pointers. You may solve it iteratively or recursively.

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 list has between 0 and 5000 nodes
  • -5000 <= Node.val <= 5000
Sample Input
Sample Output
Constraints
  • 0 to 5000 nodes
  • -5000 <= Node.val <= 5000
Test Cases
Case 1
Args: [[1,2,3,4,5]] Expected: [5,4,3,2,1]
Topics

Iterative

function reverseList(head) {
  let prev = null, curr = head;
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript