Move last m elements to the front of a given Linked List
Last Updated :
10 Nov, 2022
Given the head of a Singly Linked List and a value m, the task is to move the last m elements to the front.
Examples:
Input: 4->5->6->1->2->3 ; m = 3
Output: 1->2->3->4->5->6
Input: 0->1->2->3->4->5 ; m = 4
Output: 2->3->4->5->0->1
Algorithm:
- Use two pointers: one to store the address of the last node and other for the address of the first node.
- Traverse the list till the first node of last m nodes.
- Maintain two pointers p, q i.e., p as the first node of last m nodes & q as just before node of p.
- Make the last node next as the original list head.
- Make the next of node q as NULL.
- Set the p as the head.
Below is the implementation of the above approach.
C++
// C++ Program to move last m elements
// to front in a given linked list
#include <iostream>
using namespace std;
// A linked list node
struct Node
{
int data;
struct Node* next;
} * first, *last;
int length = 0;
// Function to print nodes
// in a given linked list
void printList(struct Node* node)
{
while (node != NULL)
{
cout << node->data <<" ";
node = node->next;
}
}
// Pointer head and p are being
// used here because, the head
// of the linked list is changed in this function.
void moveToFront(struct Node* head,
struct Node* p, int m)
{
// If the linked list is empty,
// or it contains only one node,
// then nothing needs to be done, simply return
if (head == NULL)
return;
p = head;
head = head->next;
m++;
// if m value reaches length,
// the recursion will end
if (length == m)
{
// breaking the link
p->next = NULL;
// connecting last to first &
// will make another node as head
last->next = first;
// Making the first node of
// last m nodes as root
first = head;
}
else
moveToFront(head, p, m);
}
// UTILITY FUNCTIONS
// Function to add a node at
// the beginning of Linked List
void push(struct Node** head_ref,
int new_data)
{
// allocate node
struct Node* new_node = (struct Node*)
malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// link the old list of the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
// making first & last nodes
if (length == 0)
last = *head_ref;
else
first = *head_ref;
// increase the length
length++;
}
// Driver code
int main()
{
struct Node* start = NULL;
// The constructed linked list is:
// 1->2->3->4->5
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
push(&start, 0);
cout << "Initial Linked list\n";
printList(start);
int m = 4; // no.of nodes to change
struct Node* temp;
moveToFront(start, temp, m);
cout << "\n Final Linked list\n";
start = first;
printList(start);
return 0;
}
// This code is contributed by SHUBHAMSINGH10
C
// C Program to move last m elements
// to front in a given linked list
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node {
int data;
struct Node* next;
} * first, *last;
int length = 0;
// Function to print nodes
// in a given linked list
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// Pointer head and p are being
// used here because, the head
// of the linked list is changed in this function.
void moveToFront(struct Node* head,
struct Node* p, int m)
{
// If the linked list is empty,
// or it contains only one node,
// then nothing needs to be done, simply return
if (head == NULL)
return;
p = head;
head = head->next;
m++;
// if m value reaches length,
// the recursion will end
if (length == m) {
// breaking the link
p->next = NULL;
// connecting last to first &
// will make another node as head
last->next = first;
// Making the first node of
// last m nodes as root
first = head;
}
else
moveToFront(head, p, m);
}
// UTILITY FUNCTIONS
// Function to add a node at
// the beginning of Linked List
void push(struct Node** head_ref,
int new_data)
{
// allocate node
struct Node* new_node = (struct Node*)
malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// link the old list of the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
// making first & last nodes
if (length == 0)
last = *head_ref;
else
first = *head_ref;
// increase the length
length++;
}
// Driver code
int main()
{
struct Node* start = NULL;
// The constructed linked list is:
// 1->2->3->4->5
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
push(&start, 0);
printf("\n Initial Linked list\n");
printList(start);
int m = 4; // no.of nodes to change
struct Node* temp;
moveToFront(start, temp, m);
printf("\n Final Linked list\n");
start = first;
printList(start);
return 0;
}
Java
// Java Program to move last m elements
// to front in a given linked list
class GFG
{
// A linked list node
static class Node
{
int data;
Node next;
}
static Node first, last;
static int length = 0;
// Function to print nodes
// in a given linked list
static void printList(Node node)
{
while (node != null)
{
System.out.printf("%d ", node.data);
node = node.next;
}
}
// Pointer head and p are being
// used here because, the head
// of the linked list is changed in this function.
static void moveToFront(Node head, Node p, int m)
{
// If the linked list is empty,
// or it contains only one node,
// then nothing needs to be done, simply return
if (head == null)
return;
p = head;
head = head.next;
m++;
// if m value reaches length,
// the recursion will end
if (length == m)
{
// breaking the link
p.next = null;
// connecting last to first &
// will make another node as head
last.next = first;
// Making the first node of
// last m nodes as root
first = head;
}
else
moveToFront(head, p, m);
}
// UTILITY FUNCTIONS
// Function to add a node at
// the beginning of Linked List
static Node push(Node head_ref, int new_data)
{
// allocate node
Node new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list of the new node
new_node.next = head_ref;
// move the head to point to the new node
head_ref = new_node;
// making first & last nodes
if (length == 0)
last = head_ref;
else
first = head_ref;
// increase the length
length++;
return head_ref;
}
// Driver code
public static void main(String[] args)
{
Node start = null;
// The constructed linked list is:
// 1.2.3.4.5
start = push(start, 5);
start = push(start, 4);
start = push(start, 3);
start = push(start, 2);
start = push(start, 1);
start = push(start, 0);
System.out.printf("\n Initial Linked list\n");
printList(start);
int m = 4; // no.of nodes to change
Node temp = new Node();
moveToFront(start, temp, m);
System.out.printf("\n Final Linked list\n");
start = first;
printList(start);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python Program to move last m elements
# to front in a given linked list
# A linked list node
class Node :
def __init__(self):
self.data = 0
self.next = None
first = None
last = None
length = 0
# Function to print nodes
# in a given linked list
def printList( node):
while (node != None) :
print( node.data, end=" ")
node = node.next
# Pointer head and p are being
# used here because, the head
# of the linked list is changed in this function.
def moveToFront( head, p, m):
global first
global last
global length
# If the linked list is empty,
# or it contains only one node,
# then nothing needs to be done, simply return
if (head == None):
return head
p = head
head = head.next
m= m + 1
# if m value reaches length,
# the recursion will end
if (length == m) :
# breaking the link
p.next = None
# connecting last to first &
# will make another node as head
last.next = first
# Making the first node of
# last m nodes as root
first = head
else:
moveToFront(head, p, m)
# UTILITY FUNCTIONS
# Function to add a node at
# the beginning of Linked List
def push( head_ref, new_data):
global first
global last
global length
# allocate node
new_node = Node()
# put in the data
new_node.data = new_data
# link the old list of the new node
new_node.next = (head_ref)
# move the head to point to the new node
(head_ref) = new_node
# making first & last nodes
if (length == 0):
last = head_ref
else:
first = head_ref
# increase the length
length= length + 1
return head_ref
# Driver code
start = None
# The constructed linked list is:
# 1.2.3.4.5
start = push(start, 5)
start = push(start, 4)
start = push(start, 3)
start = push(start, 2)
start = push(start, 1)
start = push(start, 0)
print("\n Initial Linked list")
printList(start)
m = 4 # no.of nodes to change
temp = None
moveToFront(start, temp, m)
print("\n Final Linked list")
start = first
printList(start)
# This code is contributed by Arnab Kundu
C#
// C# Program to move last m elements
// to front in a given linked list
using System;
class GFG
{
// A linked list node
class Node
{
public int data;
public Node next;
}
static Node first, last;
static int length = 0;
// Function to print nodes
// in a given linked list
static void printList(Node node)
{
while (node != null)
{
Console.Write("{0} ", node.data);
node = node.next;
}
}
// Pointer head and p are being used here
// because, the head of the linked list
// is changed in this function.
static void moveToFront(Node head,
Node p, int m)
{
// If the linked list is empty,
// or it contains only one node,
// then nothing needs to be done,
// simply return
if (head == null)
return;
p = head;
head = head.next;
m++;
// if m value reaches length,
// the recursion will end
if (length == m)
{
// breaking the link
p.next = null;
// connecting last to first &
// will make another node as head
last.next = first;
// Making the first node of
// last m nodes as root
first = head;
}
else
moveToFront(head, p, m);
}
// UTILITY FUNCTIONS
// Function to add a node at
// the beginning of Linked List
static Node push(Node head_ref, int new_data)
{
// allocate node
Node new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list of the new node
new_node.next = head_ref;
// move the head to point to the new node
head_ref = new_node;
// making first & last nodes
if (length == 0)
last = head_ref;
else
first = head_ref;
// increase the length
length++;
return head_ref;
}
// Driver code
public static void Main(String[] args)
{
Node start = null;
// The constructed linked list is:
// 1.2.3.4.5
start = push(start, 5);
start = push(start, 4);
start = push(start, 3);
start = push(start, 2);
start = push(start, 1);
start = push(start, 0);
Console.Write("Initial Linked list\n");
printList(start);
int m = 4; // no.of nodes to change
Node temp = new Node();
moveToFront(start, temp, m);
Console.Write("\nFinal Linked list\n");
start = first;
printList(start);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript Program to move last m elements
// to front in a given linked list
// A linked list node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
var first, last;
var length = 0;
// Function to print nodes
// in a given linked list
function printList(node) {
while (node != null) {
document.write(node.data + " ");
node = node.next;
}
}
// Pointer head and p are being used here
// because, the head of the linked list
// is changed in this function.
function moveToFront(head, p, m) {
// If the linked list is empty,
// or it contains only one node,
// then nothing needs to be done,
// simply return
if (head == null) return;
p = head;
head = head.next;
m++;
// if m value reaches length,
// the recursion will end
if (length == m) {
// breaking the link
p.next = null;
// connecting last to first &
// will make another node as head
last.next = first;
// Making the first node of
// last m nodes as root
first = head;
} else moveToFront(head, p, m);
}
// UTILITY FUNCTIONS
// Function to add a node at
// the beginning of Linked List
function push(head_ref, new_data) {
// allocate node
var new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list of the new node
new_node.next = head_ref;
// move the head to point to the new node
head_ref = new_node;
// making first & last nodes
if (length == 0) last = head_ref;
else first = head_ref;
// increase the length
length++;
return head_ref;
}
// Driver code
var start = null;
// The constructed linked list is:
// 1.2.3.4.5
start = push(start, 5);
start = push(start, 4);
start = push(start, 3);
start = push(start, 2);
start = push(start, 1);
start = push(start, 0);
document.write("Initial Linked list <br>");
printList(start);
var m = 4; // no.of nodes to change
var temp = new Node();
moveToFront(start, temp, m);
document.write("<br> Final Linked list <br>");
start = first;
printList(start);
// This code is contributed by rdtank.
</script>
Output: Initial Linked list
0 1 2 3 4 5
Final Linked list
2 3 4 5 0 1
Time Complexity: O(n), where n represents the length of the list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Similar Reads
C Program For Moving Last Element To Front Of A Given Linked List Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one t
3 min read
C# Program For Moving Last Element To Front Of A Given Linked List Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one t
3 min read
C Program For Finding The Middle Element Of A Given Linked List Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Merge first half and reversed second half of the linked list alternatively Given a linked list, the task is to rearrange the linked list in the following manner: Reverse the second half of given linked list. First element of the linked list is the first element of first half.Second element of the linked list is the first element of second half. Examples: Input: 1->2-
11 min read
C Program To Delete N Nodes After M Nodes Of A Linked List Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples: Input: M = 2, N = 2 Linked List: 1->2->3->4->5->6->7->8 Output: Linked L
3 min read