FastPrepReverse a Linked List

Reverse a Linked List

Mygate logoMygate● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

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

Reuse the existing nodes. Each node must point to the node that preceded it in the original list; the original head becomes the tail and points to null.

The input is acyclic. An empty list remains empty. Lists are displayed as arrays of their node values.

Function

reverseList(head: ListNode) → ListNode

Examples

Example 1

head = [2,5,8]return = [8,5,2]

The original last node becomes the head. The node order changes from 2 → 5 → 8 to 8 → 5 → 2.

Example 2

head = [4,4,-1]return = [-1,4,4]

Reversal preserves all three nodes, including both nodes with value 4.

Constraints

  • The list has 0 to 1000 nodes.
  • Each node value is an integer in [-10^6, 10^6].
  • Node values may repeat.
  • The input contains no cycle.

More Mygate problems

See Mygate hiring insights
public ListNode reverseList(ListNode head) {
    // Reverse the links and return the new head.
}
head[2,5,8]
expected[8,5,2]
Checking account…