Append the last M nodes to the beginning of the given linked list.
Last Updated :
22 Mar, 2023
Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.
Examples:
Input: List = 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> NULL, M = 3
Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Input: List = 8 -> 7 -> 0 -> 4 -> 1 -> NULL, M = 2
Output: 4 -> 1 -> 8 -> 7 -> 0 -> NULL
Approach: Find the first node of the last M nodes in the list, this node will be the new head node so make the next pointer of the previous node as NULL and point the last node of the original list to the head of the original list. Finally, print the updated list.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Class for a node of
// the linked list
struct Node {
// Data and the pointer
// to the next node
int data;
Node* next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
// Function to print the linked list
void printList(Node* node)
{
while (node != NULL) {
cout << (node->data) << " -> ";
node = node->next;
}
cout << "NULL";
}
// Recursive function to return the
// count of nodes in the linked list
int cntNodes(Node* node)
{
if (node == NULL)
return 0;
return (1 + cntNodes(node->next));
}
// Function to update and print
// the updated list nodes
void updateList(Node* head, int m)
{
// Total nodes in the list
int cnt = cntNodes(head);
if (cnt != m && m < cnt) {
// Count of nodes to be skipped
// from the beginning
int skip = cnt - m;
Node* prev = NULL;
Node* curr = head;
// Skip the nodes
while (skip > 0) {
prev = curr;
curr = curr->next;
skip--;
}
// Change the pointers
prev->next = NULL;
Node* tempHead = head;
head = curr;
// Find the last node
while (curr->next != NULL)
curr = curr->next;
// Connect it to the head
// of the sub list
curr->next = tempHead;
}
// Print the updated list
printList(head);
}
// Driver code
int main()
{
// Create the list
Node* head = new Node(4);
head->next = new Node(5);
head->next->next = new Node(6);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(2);
head->next->next->next->next->next = new Node(3);
int m = 3;
updateList(head, m);
return 0;
}
// This code is contributed by rutvik_56
Java
// Java implementation of the approach
class GFG {
// Class for a node of
// the linked list
static class Node {
// Data and the pointer
// to the next node
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
// Function to print the linked list
static void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " -> ");
node = node.next;
}
System.out.print("NULL");
}
// Recursive function to return the
// count of nodes in the linked list
static int cntNodes(Node node)
{
if (node == null)
return 0;
return (1 + cntNodes(node.next));
}
// Function to update and print
// the updated list nodes
static void updateList(Node head, int m)
{
// Total nodes in the list
int cnt = cntNodes(head);
if (cnt != m && m < cnt) {
// Count of nodes to be skipped
// from the beginning
int skip = cnt - m;
Node prev = null;
Node curr = head;
// Skip the nodes
while (skip > 0) {
prev = curr;
curr = curr.next;
skip--;
}
// Change the pointers
prev.next = null;
Node tempHead = head;
head = curr;
// Find the last node
while (curr.next != null)
curr = curr.next;
// Connect it to the head
// of the sub list
curr.next = tempHead;
}
// Print the updated list
printList(head);
}
// Driver code
public static void main(String[] args)
{
// Create the list
Node head = new Node(4);
head.next = new Node(5);
head.next.next = new Node(6);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(3);
int m = 3;
updateList(head, m);
}
}
Python3
# Python3 implementation of the approach
# Class for a node of
# the linked list
class newNode:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# Function to print the linked list
def printList(node):
while (node != None):
print(node.data, "->", end=" ")
node = node.next
print("NULL")
# Recursive function to return the
# count of nodes in the linked list
def cntNodes(node):
if (node == None):
return 0
return (1 + cntNodes(node.next))
# Function to update and print
# the updated list nodes
def updateList(head, m):
# Total nodes in the list
cnt = cntNodes(head)
if (cnt != m and m < cnt):
# Count of nodes to be skipped
# from the beginning
skip = cnt - m
prev = None
curr = head
# Skip the nodes
while (skip > 0):
prev = curr
curr = curr.next
skip -= 1
# Change the pointers
prev.next = None
tempHead = head
head = curr
# Find the last node
while (curr.next != None):
curr = curr.next
# Connect it to the head
# of the sub list
curr.next = tempHead
# Print the updated list
printList(head)
# Driver code
# Create the list
head = newNode(4)
head.next = newNode(5)
head.next.next = newNode(6)
head.next.next.next = newNode(1)
head.next.next.next.next = newNode(2)
head.next.next.next.next.next = newNode(3)
m = 3
updateList(head, m)
# This code is contributed by shubhamsingh10
C#
// C# implementation of the approach
using System;
class GFG {
// Class for a node of
// the linked list
class Node {
// Data and the pointer
// to the next node
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
// Function to print the linked list
static void printList(Node node)
{
while (node != null) {
Console.Write(node.data + " -> ");
node = node.next;
}
Console.Write("NULL");
}
// Recursive function to return the
// count of nodes in the linked list
static int cntNodes(Node node)
{
if (node == null)
return 0;
return (1 + cntNodes(node.next));
}
// Function to update and print
// the updated list nodes
static void updateList(Node head, int m)
{
// Total nodes in the list
int cnt = cntNodes(head);
if (cnt != m && m < cnt) {
// Count of nodes to be skipped
// from the beginning
int skip = cnt - m;
Node prev = null;
Node curr = head;
// Skip the nodes
while (skip > 0) {
prev = curr;
curr = curr.next;
skip--;
}
// Change the pointers
prev.next = null;
Node tempHead = head;
head = curr;
// Find the last node
while (curr.next != null)
curr = curr.next;
// Connect it to the head
// of the sub list
curr.next = tempHead;
}
// Print the updated list
printList(head);
}
// Driver code
public static void Main(String[] args)
{
// Create the list
Node head = new Node(4);
head.next = new Node(5);
head.next.next = new Node(6);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(3);
int m = 3;
updateList(head, m);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript implementation of the approach
// Class for a node of
// the linked list
class Node {
// Data and the pointer
// to the next node
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to print the linked list
function printList(node) {
while (node != null) {
document.write(node.data + " -> ");
node = node.next;
}
document.write("NULL");
}
// Recursive function to return the
// count of nodes in the linked list
function cntNodes(node) {
if (node == null) return 0;
return 1 + cntNodes(node.next);
}
// Function to update and print
// the updated list nodes
function updateList(head, m) {
// Total nodes in the list
var cnt = cntNodes(head);
if (cnt != m && m < cnt) {
// Count of nodes to be skipped
// from the beginning
var skip = cnt - m;
var prev = null;
var curr = head;
// Skip the nodes
while (skip > 0) {
prev = curr;
curr = curr.next;
skip--;
}
// Change the pointers
prev.next = null;
var tempHead = head;
head = curr;
// Find the last node
while (curr.next != null) curr = curr.next;
// Connect it to the head
// of the sub list
curr.next = tempHead;
}
// Print the updated list
printList(head);
}
// Driver code
// Create the list
var head = new Node(4);
head.next = new Node(5);
head.next.next = new Node(6);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(3);
var m = 3;
updateList(head, m);
// This code is contributed by rdtank.
</script>
Output1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
METHOD 2:
We Will use modification of runner's technique :-
1. find the kth node from end using runner technique and do the following modifications
2. now we have to update our pointers as
a) fast->next will be pointing to head,
b)slow->next will be new head,
c)last node will be the slow->next hence it should point to null
C++
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
void insertAtTail(node*& head, int x)
{
if (head == NULL) {
head = new node(x);
return;
}
node* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
node* t = new node(x);
curr->next = t;
}
void print(node* head)
{
node* curr = head;
while (curr != NULL) {
cout << curr->data << " -> ";
curr = curr->next;
}
cout << "NULL\n";
}
node* appendK(node* head, int k)
{
node* fast = head;
node* slow = head;
for (int i = 0; i < k; i++) {
fast = fast->next;
}
while (fast->next != NULL) {
slow = slow->next;
fast = fast->next;
}
// cout<<"data"<<" "<<slow->data<<" "<<fast->data<<endl;
fast->next = head;
head = slow->next;
slow->next = NULL;
return head;
}
int main()
{
node* head = NULL;
int n;
n = 6;
insertAtTail(head, 4);
insertAtTail(head, 5);
insertAtTail(head, 6);
insertAtTail(head, 1);
insertAtTail(head, 2);
insertAtTail(head, 3);
int k;
k = 3;
head = appendK(head, k % n);
print(head);
return 0;
}
Java
// Java code to the above approach
import java.io.*;
class GFG {
class Node {
int data;
Node next;
Node(int x)
{
data = x;
next = null;
}
}
public Node insertAtTail(Node head, int x)
{
if (head == null) {
head = new Node(x);
return head;
}
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
Node t = new Node(x);
curr.next = t;
return head;
}
public void print(Node head)
{
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " -> ");
curr = curr.next;
}
System.out.print("NULL\n");
}
public Node appendK(Node head, int k)
{
Node fast = head;
Node slow = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
public static void main(String[] args)
{
GFG l = new GFG();
Node head = null;
int n = 6;
head = l.insertAtTail(head, 4);
head = l.insertAtTail(head, 5);
head = l.insertAtTail(head, 6);
head = l.insertAtTail(head, 1);
head = l.insertAtTail(head, 2);
head = l.insertAtTail(head, 3);
int k = 3;
head = l.appendK(head, k % n);
l.print(head);
}
}
// This code is contributed by lokesh (lokeshmvs21).
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def insertAtTail(self, head, x):
if head is None:
head = Node(x)
return head
curr = head
while curr.next is not None:
curr = curr.next
t = Node(x)
curr.next = t
return head
def printList(self, head):
curr = head
while curr is not None:
print(curr.data, end=" -> ")
curr = curr.next
print("NULL")
def appendK(self, head, k):
fast = head
slow = head
for i in range(k):
fast = fast.next
while fast.next is not None:
slow = slow.next
fast = fast.next
fast.next = head
head = slow.next
slow.next = None
return head
if __name__ == "__main__":
l = LinkedList()
head = None
n = 6
head = l.insertAtTail(head, 4)
head = l.insertAtTail(head, 5)
head = l.insertAtTail(head, 6)
head = l.insertAtTail(head, 1)
head = l.insertAtTail(head, 2)
head = l.insertAtTail(head, 3)
k = 3
head = l.appendK(head, k % n)
l.printList(head)
JavaScript
// JavaScript code to the above approach
class Node {
constructor(x){
this.data = x;
this.next = null;
}
}
function insertAtTail( head, x)
{
if (head == null) {
head = new Node(x);
return head;
}
let curr = head;
while (curr.next != null) {
curr = curr.next;
}
let t = new Node(x);
curr.next = t;
return head;
}
function print(head)
{
let curr = head;
while (curr != null) {
process.stdout.write(curr.data + " -> ");
curr = curr.next;
}
console.log("NULL");
}
function appendK(head, k)
{
let fast = head;
let slow = head;
for (let i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
let head = null;
let n = 6;
head = insertAtTail(head, 4);
head = insertAtTail(head, 5);
head = insertAtTail(head, 6);
head = insertAtTail(head, 1);
head = insertAtTail(head, 2);
head = insertAtTail(head, 3);
let k = 3;
head = appendK(head, k % n);
print(head);
// This code is contributed by Nidhi goel.
C#
// C# code to the above approach
using System;
public class GFG {
class Node {
public int data;
public Node next;
public Node(int x)
{
data = x;
next = null;
}
}
Node insertAtTail(Node head, int x)
{
if (head == null) {
head = new Node(x);
return head;
}
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
Node t = new Node(x);
curr.next = t;
return head;
}
void print(Node head)
{
Node curr = head;
while (curr != null) {
Console.Write(curr.data + " -> ");
curr = curr.next;
}
Console.Write("NULL\n");
}
Node appendK(Node head, int k)
{
Node fast = head;
Node slow = head;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
static public void Main()
{
GFG l = new GFG();
Node head = null;
int n = 6;
head = l.insertAtTail(head, 4);
head = l.insertAtTail(head, 5);
head = l.insertAtTail(head, 6);
head = l.insertAtTail(head, 1);
head = l.insertAtTail(head, 2);
head = l.insertAtTail(head, 3);
int k = 3;
head = l.appendK(head, k % n);
l.print(head);
}
}
// This code is contributed by lokesh (lokeshmvs21).
Output1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Time complexity: O(n) where n is size of given linked list
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem