vastpin.blogg.se

Reverse linked list
Reverse linked list





reverse linked list

ListNode reverseFromMToN(ListNode head, int m, int n) Pseudo-Code ListNode reverse(ListNode head) Now, we will pass revStart to the reverse function and then will attach the reversed part with revStart and revEnd to get the reversed linked list.

reverse linked list

revNext → for storing the next node, i.e. revEnd → for storing the ending node(nth) of reversal.Ĥ. revStart → for storing the starting(mth) node of reversal.ģ. revPrev → for storing the previous node, i.e. But, before passing the mth node we need to traverse to the nth node and cut its link with (n+1)th node if present.Īlso we have to save the the (m-1) node and also (n+1)th node address so that we can link the reversed part of the linked list again with the original linked list. We need to find the mth node and pass it to the reverse function (which will reverse the given part). Since we have to reverse a part of the given linked list obviously we need the concept of reversing the linked list. Node Structure of the Linked List: class ListNode Is the value of m and n always different? ( Ans: No, it can be same too).Then, return the head of the m to n reversed Linked List.įor Example: Input: 15->20->25->30->35->NULL, m = 2 and n = 4 Step 2: Invoke the reverseList () method for the remaining portion of the linked list. Step 1: Split the list given into two parts - the first node and the rest of the linked list. Problem Description: Given a head pointer of a Linked List and two positions say m and n, you have to reverse the given Linked List only from position m to position n. The following are some steps involved in the recursive approach. Difficulty: Medium Asked in: Amazon, Facebook, Microsoft Understanding the problem







Reverse linked list