Frontend School

Reverse a Singly Linked List Iteratively

DSA
easy

Reverse a Singly Linked List Iteratively

Easy
Linked List
Reversal
Pointers
Iteration
Data Structures
Algorithms
Coding-Interview
practice

Overview

This problem challenges you to reverse the order of nodes in a singly linked list. Given the head of a linked list, your task is to return the head of the reversed list. This fundamental operation is a common interview question and tests your understanding of pointer manipulation and linked list traversal.

What you need to do / Task

Implement a function reverseList that takes the head of a singly linked list as input and returns the new head of the list after its nodes have been reversed.

Input & output

Input:

  • head: A ListNode object, representing the head of a singly linked list. It can be null if the list is empty.

Output:

  • A ListNode object, representing the head of the reversed linked list. This will be null if the input list was empty.

ListNode Definition

For your convenience, the ListNode class is defined as follows:

class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val?: number, next?: ListNode | null) {
    this.val = (val===undefined ? 0 : val);
    this.next = (next===undefined ? null : next);
  }
}

(The JavaScript definition is similar.)

Clarifications

  • Q: What should be returned if the input list is empty or contains only one node?
    • A: If the list is empty (head is null) or contains a single node, return the head itself. The reversal operation doesn't change these specific cases.
  • Q: Should I create a new linked list or modify the existing one?
    • A: You must modify the existing linked list in-place. Do not create new ListNode objects for the reversal.
  • Q: What about cycles in the linked list?
    • A: Assume there are no cycles in the input linked list.

Examples

1

Example 1

Input:

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

Output:

[5,4,3,2,1]

Note:

The original list is 1 -> 2 -> 3 -> 4 -> 5. After reversing, it becomes 5 -> 4 -> 3 -> 2 -> 1.

2

Example 2

Input:

head = [1,2]

Output:

[2,1]

Note:

The original list is 1 -> 2. After reversing, it becomes 2 -> 1.

3

Example 3

Input:

head = []

Output:

[]

Note:

An empty list remains empty after reversal.

Constraints

Constraints & assumptions

  • The number of nodes in the list is in the range [0, 5000].
  • -5000 <= Node.val <= 5000.

What graders evaluate

  • The reversed list must be structurally correct, maintaining all original nodes with their values.
  • The solution must operate in O(N) time complexity, where N is the number of nodes in the list.
  • The solution must operate in O(1) space complexity, excluding the input list itself.
  • The original list must be modified in-place; no new ListNode objects should be created for the reversal process.

Loading editor...