Skip to content
Official PYQ · 2022

GATE CS 2022 Q5 — Linked Lists

Explain with AI

Consider the problem of reversing a singly linked list. To take an example, given the linked list below,

the reversed linked list should look like

Which one of the following statements is TRUE\text{TRUE} about the time complexity of algorithms that solve the above problem in O(1)O(1) space?

Choose one option
View worked solution

Answer: A

To reverse a singly linked list of size nn in-place (using O(1)O(1) auxiliary space), we can use an iterative approach with three pointers: prev, curr, and next.

Iterative Algorithm:

  1. Initialize three pointers: prev = NULL, curr = head, and next = NULL.
  2. Iterate through the linked list until curr is NULL:
    • Store the next node: next = curr->next
    • Reverse the current node's pointer: curr->next = prev
    • Move pointers one step forward: prev = curr, curr = next
  3. Set the head of the reversed list: head = prev.

Complexity Analysis:

  • Time Complexity: The algorithm traverses the list of nn nodes exactly once. At each node, it performs a constant number of pointer updates. Thus, the worst-case time complexity is θ(n)\theta(n).
  • Space Complexity: The algorithm only uses three extra pointer variables, which requires O(1)O(1) auxiliary space.

Since we can successfully reverse the list in θ(n)\theta(n) time and O(1)O(1) space, Option A is the correct statement.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Linked Lists questions