VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-sublist-linked-list/

⇱ Reverse a sublist of linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse a sublist of linked list

Last Updated : 27 Aug, 2024

Given a linked list and positions m and n. We need to reverse the linked list from position m to n.

Examples:  

Input : linkedlist : 10->20->30->40->50->60->70->NULL , m = 3 and n = 6
Output : 10->20->60->50->40->30->70->NULL
Explanation: Linkedlist reversed starting from the node mi.e. 30 and n i.e. 60

👁 Reverse-a-sublist-of-linked-list
Example of Reverse a sublist of linked list


Input : linkedlist : 1->2->3->4->5->6->NULL , m = 2 and n = 4
Output : 1->4->3->2->5->6->NULL
Explanation: Linkedlist reversed starting from the node mi.e. 2 and n i.e. 4

[Expected Approach - 1] Using Two Traversal - O(n) time and O(1) Space:

The idea is to reverse a segment of the linked list by locating the start and end nodes, removing the links and reversing the segment using standard reverse function, and then reattaching it back to the main list.

Step-by-step approach :

  • Find the start and end positions of the linked list by running a loop.
  • Unlink the portion of the list that needs to be reversed from the rest of the list.
  • Reverse the unlinked portion using the standard linked list reverse function.
  • Reattach the reversed portion to the main list.

Below is the implementation of above approach:


Output
Original list: 10 20 30 40 50 60 70 NULL
Modified list: 10 20 60 50 40 30 70 NULL

Time Complexity: O(n), Here n is the number of nodes in the linked list. In the worst case we need to traverse the list twice.
Auxiliary Space: O(1).

[Expected Approach - 2] Using Single Traversal - O(n) time and O(1) Space:

The idea is to get pointers to the head and tail of the reversed segment, the node before the mth node, and the node after the nth node and then reverse the segment and reconnect the links appropriately.

Follow the steps below to solve the problem:

  • Get the pointer to the head and tail of the reversed linked list.
  • Get the pointer to the node before mth and node after nth node.
  • Reverse the list using standard linked list reverse function.
  • Connect back the links properly.

Step-by-step approach :


Output
Original list: 10 20 30 40 50 60 70 NULL
Modified list: 10 20 60 50 40 30 70 NULL

Time Complexity: O(n) ,where n the size of the linked list.
Auxiliary Space: O(1).

Comment
Article Tags: