Open In App

Reverse a sublist of linked list

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

Examples:  

Input : 10->20->30->40->50->60->70->NULL
        m = 3, n = 6
Output : 10->20->60->50->40->30->70->NULL

Input :  1->2->3->4->5->6->NULL 
         m = 2, n = 4
Output : 1->4->3->2->5->6->NULL

To reverse the linked list from position m to n, we find addresses of start and end position of the linked list by running a loop, and then we unlink this part from the rest of the list and then use the normal linked list reverse function which we have earlier used for reversing the complete linked list, and use it to reverse the portion of the linked list which need to be reversed. After reversal, we again attach the portion reversed to the main list.

C++





C




<div id="highlighter_887091" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="comments">// C program to reverse a linked list </code></div><div class="line number2 index1 alt1"><code class="comments">// from position m to position n </code></div><div class="line number3 index2 alt2"><code class="preprocessor">#include <stdio.h> </code></div><div class="line number4 index3 alt1"><code class="preprocessor">#include <stdlib.h> </code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code> </div><div class="line number6 index5 alt1"><code class="comments">// Linked list node </code></div><div class="line number7 index6 alt2"><code class="keyword bold">typedef</code> <code class="keyword bold">struct</code> <code class="plain">Node { </code></div><div class="line number8 index7 alt1"><code class="undefined spaces">    </code><code class="color1 bold">int</code> <code class="plain">data; </code></div><div class="line number9 index8 alt2"><code class="undefined spaces">    </code><code class="keyword bold">struct</code> <code class="plain">Node* next; </code></div><div class="line number10 index9 alt1"><code class="plain">} Node; </code></div><div class="line number11 index10 alt2"><code class="undefined spaces"> </code> </div><div class="line number12 index11 alt1"><code class="comments">// function used to reverse a linked list </code></div><div class="line number13 index12 alt2"><code class="plain">Node* reverse(Node* head) </code></div><div class="line number14 index13 alt1"><code class="plain">{ </code></div><div class="line number15 index14 alt2"><code class="undefined spaces">    </code><code class="plain">Node* prev = NULL; </code></div><div class="line number16 index15 alt1"><code class="undefined spaces">    </code><code class="plain">Node* curr = head; </code></div><div class="line number17 index16 alt2"><code class="undefined spaces">    </code><code class="keyword bold">while</code> <code class="plain">(curr) { </code></div><div class="line number18 index17 alt1"><code class="undefined spaces">        </code><code class="plain">Node* next = curr->next; </code></div><div class="line number19 index18 alt2"><code class="undefined spaces">        </code><code class="plain">curr->next = prev; </code></div><div class="line number20 index19 alt1"><code class="undefined spaces">        </code><code class="plain">prev = curr; </code></div><div class="line number21 index20 alt2"><code class="undefined spaces">        </code><code class="plain">curr = next; </code></div><div class="line number22 index21 alt1"><code class="undefined spaces">    </code><code class="plain">} </code></div><div class="line number23 index22 alt2"><code class="undefined spaces">    </code><code class="keyword bold">return</code> <code class="plain">prev; </code></div><div class="line number24 index23 alt1"><code class="plain">} </code></div><div class="line number25 index24 alt2"><code class="undefined spaces"> </code> </div><div class="line number26 index25 alt1"><code class="comments">// function used to reverse a linked list from position m to n </code></div><div class="line number27 index26 alt2"><code class="plain">Node* reverseBetween(Node* head, </code><code class="color1 bold">int</code> <code class="plain">m, </code><code class="color1 bold">int</code> <code class="plain">n) </code></div><div class="line number28 index27 alt1"><code class="plain">{ </code></div><div class="line number29 index28 alt2"><code class="undefined spaces">    </code><code class="keyword bold">if</code> <code class="plain">(m == n) </code></div><div class="line number30 index29 alt1"><code class="undefined spaces">        </code><code class="keyword bold">return</code> <code class="plain">head; </code></div><div class="line number31 index30 alt2"><code class="undefined spaces"> </code> </div><div class="line number32 index31 alt1"><code class="undefined spaces">    </code><code class="comments">// revs and revend is start and end respectively of the </code></div><div class="line number33 index32 alt2"><code class="undefined spaces">    </code><code class="comments">// portion of the linked list which need to be reversed. </code></div><div class="line number34 index33 alt1"><code class="undefined spaces">    </code><code class="comments">// revs_prev is previous of starting position and </code></div><div class="line number35 index34 alt2"><code class="undefined spaces">    </code><code class="comments">// revend_next is next of end of list to be reversed. </code></div><div class="line number36 index35 alt1"><code class="undefined spaces">    </code><code class="plain">Node *revs = NULL, *revs_prev = NULL; </code></div><div class="line number37 index36 alt2"><code class="undefined spaces">    </code><code class="plain">Node *revend = NULL, *revend_next = NULL; </code></div><div class="line number38 index37 alt1"><code class="undefined spaces"> </code> </div><div class="line number39 index38 alt2"><code class="undefined spaces">    </code><code class="comments">// Find values of above pointers. </code></div><div class="line number40 index39 alt1"><code class="undefined spaces">    </code><code class="color1 bold">int</code> <code class="plain">i = 1; </code></div><div class="line number41 index40 alt2"><code class="undefined spaces">    </code><code class="plain">Node* curr = head; </code></div><div class="line number42 index41 alt1"><code class="undefined spaces">    </code><code class="keyword bold">while</code> <code class="plain">(curr && i <= n) { </code></div><div class="line number43 index42 alt2"><code class="undefined spaces">        </code><code class="keyword bold">if</code> <code class="plain">(i < m) </code></div><div class="line number44 index43 alt1"><code class="undefined spaces">            </code><code class="plain">revs_prev = curr; </code></div><div class="line number45 index44 alt2"><code class="undefined spaces">        </code><code class="keyword bold">if</code> <code class="plain">(i == m) </code></div><div class="line number46 index45 alt1"><code class="undefined spaces">            </code><code class="plain">revs = curr; </code></div><div class="line number47 index46 alt2"><code class="undefined spaces">        </code><code class="keyword bold">if</code> <code class="plain">(i == n) { </code></div><div class="line number48 index47 alt1"><code class="undefined spaces">            </code><code class="plain">revend = curr; </code></div><div class="line number49 index48 alt2"><code class="undefined spaces">            </code><code class="plain">revend_next = curr->next; </code></div><div class="line number50 index49 alt1"><code class="undefined spaces">        </code><code class="plain">} </code></div><div class="line number51 index50 alt2"><code class="undefined spaces">        </code><code class="plain">curr = curr->next; </code></div><div class="line number52 index51 alt1"><code class="undefined spaces">        </code><code class="plain">i++; </code></div><div class="line number53 index52 alt2"><code class="undefined spaces">    </code><code class="plain">} </code></div><div class="line number54 index53 alt1"><code class="undefined spaces">    </code><code class="plain">revend->next = NULL; </code></div><div class="line number55 index54 alt2"><code class="undefined spaces">    </code><code class="comments">// Reverse linked list starting with revs. </code></div><div class="line number56 index55 alt1"><code class="undefined spaces">    </code><code class="plain">revend = reverse(revs); </code></div><div class="line number57 index56 alt2"><code class="undefined spaces">    </code><code class="comments">// If starting position was not head </code></div><div class="line number58 index57 alt1"><code class="undefined spaces">    </code><code class="keyword bold">if</code> <code class="plain">(revs_prev) </code></div><div class="line number59 index58 alt2"><code class="undefined spaces">        </code><code class="plain">revs_prev->next = revend; </code></div><div class="line number60 index59 alt1"><code class="undefined spaces">    </code><code class="comments">// If starting position was head </code></div><div class="line number61 index60 alt2"><code class="undefined spaces">    </code><code class="keyword bold">else</code></div><div class="line number62 index61 alt1"><code class="undefined spaces">        </code><code class="plain">head = revend; </code></div><div class="line number63 index62 alt2"><code class="undefined spaces">    </code><code class="plain">revs->next = revend_next; </code></div><div class="line number64 index63 alt1"><code class="undefined spaces">    </code><code class="keyword bold">return</code> <code class="plain">head; </code></div><div class="line number65 index64 alt2"><code class="plain">} </code></div><div class="line number66 index65 alt1"><code class="undefined spaces"> </code> </div><div class="line number67 index66 alt2"><code class="keyword bold">void</code> <code class="plain">print(Node* head) </code></div><div class="line number68 index67 alt1"><code class="plain">{ </code></div><div class="line number69 index68 alt2"><code class="undefined spaces">    </code><code class="keyword bold">while</code> <code class="plain">(head != NULL) { </code></div><div class="line number70 index69 alt1"><code class="undefined spaces">        </code><code class="functions bold">printf</code><code class="plain">(</code><code class="string">"%d "</code><code class="plain">, head->data); </code></div><div class="line number71 index70 alt2"><code class="undefined spaces">        </code><code class="plain">head = head->next; </code></div><div class="line number72 index71 alt1"><code class="undefined spaces">    </code><code class="plain">} </code></div><div class="line number73 index72 alt2"><code class="undefined spaces">    </code><code class="functions bold">printf</code><code class="plain">(</code><code class="string">"\n"</code><code class="plain">); </code></div><div class="line number74 index73 alt1"><code class="plain">} </code></div><div class="line number75 index74 alt2"><code class="undefined spaces"> </code> </div><div class="line number76 index75 alt1"><code class="comments">// function to add a new node at the beginning of the list </code></div><div class="line number77 index76 alt2"><code class="keyword bold">void</code> <code class="plain">push(Node** head_ref, </code><code class="color1 bold">int</code> <code class="plain">new_data) </code></div><div class="line number78 index77 alt1"><code class="plain">{ </code></div><div class="line number79 index78 alt2"><code class="undefined spaces">    </code><code class="plain">Node* new_node = (Node*)</code><code class="functions bold">malloc</code><code class="plain">(</code><code class="keyword bold">sizeof</code><code class="plain">(Node)); </code></div><div class="line number80 index79 alt1"><code class="undefined spaces">    </code><code class="plain">new_node->data = new_data; </code></div><div class="line number81 index80 alt2"><code class="undefined spaces">    </code><code class="plain">new_node->next = (*head_ref); </code></div><div class="line number82 index81 alt1"><code class="undefined spaces">    </code><code class="plain">(*head_ref) = new_node; </code></div><div class="line number83 index82 alt2"><code class="plain">} </code></div><div class="line number84 index83 alt1"><code class="undefined spaces"> </code> </div><div class="line number85 index84 alt2"><code class="comments">// Driver code </code></div><div class="line number86 index85 alt1"><code class="color1 bold">int</code> <code class="plain">main() </code></div><div class="line number87 index86 alt2"><code class="plain">{ </code></div><div class="line number88 index87 alt1"><code class="undefined spaces">    </code><code class="plain">Node* head = NULL; </code></div><div class="line number89 index88 alt2"><code class="undefined spaces">    </code><code class="plain">push(&head, 70); </code></div><div class="line number90 index89 alt1"><code class="undefined spaces">    </code><code class="plain">push(&head, 60); </code></div><div class="line number91 index90 alt2"><code class="undefined spaces">    </code><code class="plain">push(&head, 50); </code></div><div class="line number92 index91 alt1"><code class="undefined spaces">    </code><code class="plain">push(&head, 40); </code></div><div class="line number93 index92 alt2"><code class="undefined spaces">    </code><code class="plain">push(&head, 30); </code></div><div class="line number94 index93 alt1"><code class="undefined spaces">    </code><code class="plain">push(&head, 20); </code></div><div class="line number95 index94 alt2"><code class="undefined spaces">    </code><code class="plain">push(&head, 10); </code></div><div class="line number96 index95 alt1"><code class="undefined spaces">    </code><code class="plain">reverseBetween(head, 3, 6); </code></div><div class="line number97 index96 alt2"><code class="undefined spaces">    </code><code class="plain">print(head); </code></div><div class="line number98 index97 alt1"><code class="undefined spaces">    </code><code class="keyword bold">return</code> <code class="plain">0; </code></div><div class="line number99 index98 alt2"><code class="plain">} </code></div><div class="line number100 index99 alt1"><code class="undefined spaces"> </code> </div><div class="line number101 index100 alt2"><code class="comments">// This code is contributed by Aditya Kumar (adityakumar129)</code></div></div></td></tr></tbody></table></div>


Java





Python3





C#





Javascript





Output

10 20 60 50 40 30 70 

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), As constant extra space is used.

Method 2: (single traversal)

In this method we need to traverse the list only once in the worst case. The algorithm makes used of the idea to reverse a normal linked list. Below is the algorithm:

  • 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 as discussed in this  post.
  • Connect back the links properly.

Implementation of the above approach:

C++





Java





Python3




# Python3 program to reverse a linked list
# from position m to position n
  
# Linked list node
class Node:
      
    def __init__(self, data):
          
        self.data = data
        self.next = None
  
def reverse(head):
  
    prev = None
    curr = head
  
    while (curr):
        next = curr.next
        curr.next = prev
        prev = curr
        curr = next
      
    return prev
  
# Function used to reverse a linked list
# from position m to n 
def reverseBetween(head, m, n):
  
          # First move the current pointer to the node from
        # where we have to reverse the linked list
        curr = head
        prev = None
        # prev points to the node before mth node
        i = 1
        while i<m: 
            prev = curr
            curr = curr.next
            i+=1
          
        # This pointer stores the pointer to the head of
        # the reversed linkedlist
        rtail = curr
        # This pointer stores the pointer to the tail of
        # the reversed linkedlist
        rhead = None
        # Now reverse the linked list from m to n nodes
        while (i <= n):
            temp = curr.next
            curr.next = rhead
            rhead = curr
            curr = temp
            i+=1
          
        # if prev is not null it means that some of the
        # nodes exits before m ( or if m!=1)
        if prev:
            prev.next = rhead
        else:
            head = rhead
        # at this point curr will point to the next of nth
        # node where we will connect the tail of the
        # reversed linked list
        rtail.next = curr
        # at the end return the new head.
        return head
  
def prints(head):
  
    while (head != None):
        print(head.data, end = ' ')
        head = head.next
          
    print()
  
# Function to add a new node at the
# beginning of the list
def push(head_ref, new_data):
  
    new_node = Node(new_data)
    new_node.data = new_data
    new_node.next = (head_ref)
    (head_ref) = new_node
    return head_ref
  
# Driver code
if __name__=='__main__':
      
    head = None
    head = push(head, 70)
    head = push(head, 60)
    head = push(head, 50)
    head = push(head, 40)
    head = push(head, 30)
    head = push(head, 20)
    head = push(head, 10)
      
    reverseBetween(head, 3, 6)
      
    prints(head)
      
# This code is contributed by Abhijeet Kumar(abhijeet19403)


C#




// C# program to reverse a linked list
// from position m to position n
  
using System;
  
class LinkedList {
    static Node head;
  
    public class Node {
        public int data;
        public Node next;
  
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
  
    // function to add a new node at
    // the end of the list
    public void AddNode(Node node)
    {
        if (head == null)
            head = node;
        else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }
  
    // function used to reverse a linked list from position m to n
    public void reverseBetween(int m, int n)
    {
  
        // First move the current pointer to the node from
        // where we have to reverse the linked list
        Node curr = head, prev = null;
        // prev points to the node before mth node
        int i;
        for (i = 1; i < m; i++) {
            prev = curr;
            curr = curr.next;
        }
        // This pointer stores the pointer to the head of
        // the reversed linkedlist
        Node rtail = curr;
        // This pointer stores the pointer to the tail of
        // the reversed linkedlist
        Node rhead = null;
        // Now reverse the linked list from m to n nodes
        while (i <= n) {
            Node next = curr.next;
            curr.next = rhead;
            rhead = curr;
            curr = next;
            i++;
        }
        // if prev is not null it means that some of the
        // nodes exits before m ( or if m!=1)
        if (prev != null)
            prev.next = rhead;
        else
            head = rhead;
        // at this point curr will point to the next of nth
        // node where we will connect the tail of the
        // reversed linked list
        rtail.next = curr;
          
    }
     
    // function to print the list data
    public void PrintList()
    {
        Node current = head;
        while (current != null) {
            Console.Write(current.data + " ");
            current = current.next;
        }
        Console.WriteLine();
    }
}
class GFG{
    // Driver Code
    public static void Main(string[] args)
    {
        LinkedList list = new LinkedList();
        list.AddNode(new LinkedList.Node(10));
        list.AddNode(new LinkedList.Node(20));
        list.AddNode(new LinkedList.Node(30));
        list.AddNode(new LinkedList.Node(40));
        list.AddNode(new LinkedList.Node(50));
          list.AddNode(new LinkedList.Node(60));
          list.AddNode(new LinkedList.Node(70));
          
        list.reverseBetween(3,6);
  
        list.PrintList();
    }
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Javascript




<script>
// JavaScript program to reverse a linked list
// from position m to position n
  
// Linked list node
class Node{
      
    constructor(data){
          
        this.data = data
        this.next = null
    }
}
  
// Function used to reverse a linked list
// from position m to n
function reverseBetween(head, m, n){
        // First move the current pointer to the node from
        // where we have to reverse the linked list
        let curr = head;
        let prev = null;
        // prev points to the node before mth node
        let i;
        for (i = 1; i < m; i++) {
            prev = curr;
            curr = curr.next;
        }
        // This pointer stores the pointer to the head of
        // the reversed linkedlist
        let rtail = curr;
        // This pointer stores the pointer to the tail of
        // the reversed linkedlist
        let rhead = null;
        // Now reverse the linked list from m to n nodes
        while (i <= n) {
            Node next = curr.next;
            curr.next = rhead;
            rhead = curr;
            curr = next;
            i++;
        }
        // if prev is not null it means that some of the
        // nodes exits before m ( or if m!=1)
        if (prev != null)
            prev.next = rhead;
        else
            head = rhead;
        // at this point curr will point to the next of nth
        // node where we will connect the tail of the
        // reversed linked list
        rtail.next = curr;
}
  
function prints(head){
  
    while (head != null){
        document.write(head.data,' ')
        head = head.next
    }
          
    document.write("</br>")
}
  
// Function to add a new node at the
// beginning of the list
function push(head_ref, new_data){
  
    let new_node = new Node(new_data)
    new_node.data = new_data
    new_node.next = head_ref
    head_ref = new_node
    return head_ref
}
  
// Driver code
      
let head = null
head = push(head, 70)
head = push(head, 60)
head = push(head, 50)
head = push(head, 40)
head = push(head, 30)
head = push(head, 20)
head = push(head, 10)
  
reverseBetween(head, 3, 6)
  
prints(head)
  
// This code is contributed by Abhijeet Kumar(abhijeet19403)
  
</script>


Output

10 20 60 50 40 30 70 

Time Complexity: O(n), Here n is the position n till which we have to reverse the linked list. In the worst case we need to traverse the list once when n is equal to the size of the linked list and in best case time complexity can go upto O(1).
Auxiliary Space: O(1), As constant extra space is used.

 



Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads