C program to Reverse only First N Elements of a Linked List
Display a linked list in reverse: Here, we are going to implement a C program to display the linked list in reverse using recursion.
Submitted by Radib Kar, on December 26, 2018
Problem statement: Given a linked list reverse it up to first N elements without using any additional space.
Example:
N= 4 The linked list is: 1 → 2 → 3 → 4 → 5 → 6 → NULL So the output will be 4 → 3 → 2 → 1 → 5 → 6Solution:
Reversing a single linked list up to first N elements is about reversing the linking direction. We can solve the above problem by following steps:
- Building the linked list
Build the linked list by appending each node at the end. [For details refer to: Single linked list insertion] - Function to reverse the link list
As told previously, the basic idea to reverse a linked list is to reverse the direction of linking for the First N elements. This concept can be implemented without using any additional space. We need three pointers *prev, *cur, *next to implement the function. These variables are named accordingly to indicate their serving part in the function.
*prev - to store the previous node which will become ultimately the next node after reversal for current node
*cur - to store the current node
*next - to store the next node which will become current node in the next iteration.
First traverse to the node that don't need to be reversed [n+1 th], store its address to temp
Initialize *prev to temp & *next to NULL, *cur to head
Initialize count to 0 which stores the number of elements to be reversedWhile[cur!=NULL&& countnext Set cur->next to *prev Set *prev to *cur Set *cur to *next End While loop Set head to *prev - Print the reversed linked list
Example:
Let the linked list be 1 → 2 → 3 → 4 → 5 → 6 → NULL N=4 [for simplicity in understanding representing pointer to node by node value] Head is 1 Initialize: cur =1, prev=5 [ from 5 no reversal needed] next=NULL count=0 in iteration 1: next=2 cur->next=5 prev=1 cur=2 count is 1 thus reversed part: 1 → 5 → 6 → NULL in iteration 2: next=3 cur->next=1 prev=2 cur=3 count is 2 thus reversed part: 2 → 1 → 5 → 6 → NULL in iteration 3: next=4 cur->next=2 prev=3 cur=4 count is 3 thus reversed part: 3 → 2 → 1 → 5 → 6 → NULL in iteration 4: next=5 cur->next=3 prev=4 cur=5 count is 4 thus reversed part: 4 → 3 → 2 → 1 → 5 → 6 → NULL Since the count is 4 now = N thus iteration stops Final output: 4 → 3 → 2 → 1 → 5 → 6 → NULLReverse first K elements of given linked list
Given a pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by changing links between nodes.
check also Reversal of a linked list
Examples:
Input : 1->2->3->4->5->6->7->8->9->10->NULL k = 3 Output :3->2->1->4->5->6->7->8->9->10->NULL Input :10->18->20->25->35->NULL k = 2 Output :18->10->20->25->35->NULLExplanation of the method:
suppose linked list is 1->2->3->4->5->NULL and k=3
1] Traverse the linked list till K-th point.
2] Break the linked list in to two parts from k-th point. After partition linked list will look like 1->2->3->NULL & 4->5->NULL
3] Reverse first part of the linked list leave second part as it is 3->2->1->NULL and 4->5->NULL
4] Join both the parts of the linked list, we get 3->2->1->4->5->NULL
A pictorial representation of how the algorithm works
// C++ program for reversal of first k elements
// of given linked list
#include
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Function to reverse first k elements of linked list */
static void reverseKNodes[struct Node** head_ref, int k]
{
// traverse the linked list until break
// point not meet
struct Node* temp = *head_ref;
int count = 1;
while [count < k] {
temp = temp->next;
count++;
}
// backup the joint point
struct Node* joint_point = temp->next;
temp->next = NULL; // break the list
// reverse the list till break point
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while [current != NULL] {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
// join both parts of the linked list
// traverse the list until NULL is not
// found
*head_ref = prev;
current = *head_ref;
while [current->next != NULL]
current = current->next;
// joint both part of the list
current->next = joint_point;
}
/* Function to push a node */
void push[struct Node** head_ref, int new_data]
{
struct Node* new_node =
[struct Node*]malloc[sizeof[struct Node]];
new_node->data = new_data;
new_node->next = [*head_ref];
[*head_ref] = new_node;
}
/* Function to print linked list */
void printList[struct Node* head]
{
struct Node* temp = head;
while [temp != NULL] {
printf["%d ", temp->data];
temp = temp->next;
}
}
/* Driver program to test above function*/
int main[]
{
// Create a linked list 1->2->3->4->5
struct Node* head = NULL;
push[&head, 5];
push[&head, 4];
push[&head, 3];
push[&head, 2];
push[&head, 1];
// k should be less than the
// numbers of nodes
int k = 3;
cout 2->3->4->NULL Output: Linked list should be changed to, 4->3->2->1->NULL Input: Head of following linked list Input: NULL Input: 1->NULL C++
DownloadRun Code Output: Program to create a singly linked list of n nodes and display it in reverse orderExplanationIn this program, we need to create a singly linked list and display the list in reverse order. Original List Reversed List One of the approaches to solving this problem is to reach the end the of the list and display the nodes from tail to head recursively. Algorithm
SolutionPythonOutput: Original List:
1 2 3 4
Reversed List:
4 3 2 1
Output: Original List:
1 2 3 4
Reversed List:
4 3 2 1
JAVAOutput: Original List:
1 2 3 4
Reversed List:
4 3 2 1
C#Output: Original List:
1 2 3 4
Reversed List:
4 3 2 1
PHPOutput: Original List:
1 2 3 4
Reversed List:
4 3 2 1
Reverse a Linked List from position m to n-Interview ProblemDifficulty: Medium Asked in: Amazon, Facebook, Microsoft Understanding the problemProblem 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. Then, return the head of the m to n reversed Linked List. For Example: Input: 15->20->25->30->35->NULL, m = 2 and n = 4 Output: 15->30->25->20->35->NULL Input: 20->40->60->70->NULL, m = 2 and n = 3 Output: 20->60->40->70->NULLPossible follow-up questions to ask: →
Node Structure of the Linked List: class ListNode { int data ListNode next }SolutionSolution idea Since we have to reverse a part of the given linked list obviously we need the concept of reversing the linked list. We need to find the mth node and pass it to the reverse function [which will reverse the given part]. 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. Also 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. Solution steps We will use following four variable: 1. revPrev → for storing the previous node, i.e. [m-1]th node. 2. revStart → for storing the starting[mth] node of reversal. 3. revEnd → for storing the ending node[nth] of reversal. 4. revNext → for storing the next node, i.e. [n+1]th node. 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. Pseudo-CodeListNode reverse[ListNode head] { if[head == NULL || head.next == NULL] return head ListNode restPart = reverse[head.next] head.next.next = head head.next = NULL return restPart } ListNode reverseFromMToN[ListNode head, int m, int n] { if[m == n] return head int count = 1 ListNode curr = head ListNode revPrev = NULL while[count < m] { revPrev = curr curr = curr.next count = count + 1 } ListNode revStart = curr while[count < n] { curr = curr.next count = count + 1 } ListNode revEnd = curr ListNode revNext = curr.next curr.next = NULL ListNode revPart = reverse[revStart] if[revPrev] { revPrev.next.next = revNext revPrev.next = revPart } else { if[revNext] { head.next = revNext } head = revPart } return head } Complexity Analysis
Critical ideas to think
Suggested Problems to Solve
Happing Coding! Enjoy Algorithms!! AfterAcademy Data Structure And Algorithms Online Course — Admissions OpenRequired knowledgeBasic C programming, Functions, Singly Linked List, Dynamic memory allocation Algorithm to reverse a Singly Linked ListAlgorithm to reverse a Singly Linked List
%%Input : head node of the linked list
Begin:
If [head != NULL] then
prevNode ← head
head ← head.next
curNode ← head
prevNode.next ← NULL
While [head != NULL] do
head ← head.next
curNode.next ← prevNode
prevNode ← curNode
curNode ← head
End while
head ← prevNode
End if
End Python Program to Reverse only First N Elements of a Linked ListPythonServer Side ProgrammingProgramming When it is required to reverse a specific set of elements in a linked list, a method named ‘reverse_list’ is defined. This iterates through the list, and reverses the specific set of elements. Below is a demonstration for the same − Video liên quanChủ Đề |