Blind 75
19 / 75Free practice

Reverse Linked List

Easy · Linked lists

Jump to code

Reverse a singly linked list by changing its next pointers and return the new head. The list may be empty.

Examples

Example 1

head = [1,2,3,4,5]

Output: [5,4,3,2,1]

Example 2

head = [1,2]

Output: [2,1]

Constraints

  • 0 <= The length of the list <= 1000.
  • -1000 <= Node.val <= 1000

Function contract

Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.

Need a hint?

Save the next node before overwriting its pointer.

Asked in real interviews

Candidates reported versions of Reverse Linked List from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    3,
    4,
    5
  ]
]
Expected
[
  5,
  4,
  3,
  2,
  1
]
Case 2
Input
[
  [
    1,
    2
  ]
]
Expected
[
  2,
  1
]
Case 3
Input
[
  []
]
Expected
[]
Case 4
Input
[
  [
    1
  ]
]
Expected
[
  1
]
Case 5
Input
[
  [
    1,
    2,
    3
  ]
]
Expected
[
  3,
  2,
  1
]

Drafts are saved per language in this browser when storage is available.