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 about the time complexity of algorithms that solve the above problem in O(1) space?
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 about the time complexity of algorithms that solve the above problem in O(1) space? Correct Answer The best algorithm for the problem takes <span style="">θ(n)</span> time in the worst case.
The correct answer is option 1.
Concept:
Single linked list:
A single linked list is a sort of unidirectional linked list that may only be traversed in one way, from head to final node (tail). A node is a name for each element in a linked list. A single node includes data as well as a pointer to the next node, which aids in the list's structure.
Explanation:
The time complexity of reversing a linked list is linear in time i.e O(n) where n is the size of the linked list.
Algorithm:
- Initialize three-pointers prev as NULL, curr as head and next as NULL.
- Iterate through the linked list. In loop, do following.
// Before changing next of current, store next node
next = curr->next
// Now change next of current This is where actual reversing happens
curr->next = prev
// Move prev and curr one step forward
prev = curr
curr = next
Analysis:
- Initialize three-pointers prev as NULL, curr as head and next as NULL.
- Iterate through the linked list,
- And check whether there are any nodes in the linked list then move forward to the nodes by changing the nodes allocations.
- Before changing the next of current, store the next node.
- Now change next of current This is where actual reversing happens with curr->next = prev.
- Move prev and curr one step forward with, prev = curr and curr = next.
So we need to traverse the whole linked list in the given linked list it takes n time to travel all elements in the linked list. So the best algorithm for the problem takes θ(n) time in the worst case.
Hence the correct answer is the best algorithm for the problem that takes θ(n) time in the worst case.