×

Rotate a Singly Linked List

Rotate a Singly Linked List

This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this list by k nodes anti-clockwise where k is a positive number.

Example:

        List is: 2 -> 4 -> 6 -> 8 -> 10 -> 12                       k: 4

        Output: 10 -> 12 -> 2 -> 4 -> 6 -> 8

NOTE: Assume that k is smaller than the length of the linked list.

Method-1:

For rotating the linked list, we need to change the next of the kth node to the NULL. We will change the next of the last node to the previous head node, and then we need to change the head to (k+1)th node.

We will traverse the list from the starting to the kth node. We need to store the pointer to the kth node. We can get (k+1)th node using kthNode  ->  next. We will keep traversing till the end and store the pointer to the last node also. Finally, we will change pointers as we discussed above.

C program to rotate a linked list anti-clockwise by Method-1

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node *)malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // Function for rotating the linked list
 void rotate(struct node * head, int k)
 {
     if (k == 0)
         return;
     struct node* curr = head;
     int count = 1;
     while (count < k && curr != NULL) {
         curr = curr -> next;
         count++;
     }
     if (curr == NULL)
         return;
     struct node* temp = curr;
     while (curr -> next != NULL)
         curr = curr -> next;
     curr -> next = head;
     head = temp -> next;
     temp -> next = NULL;
     start = head;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d ->  ",t -> info);
                         t = t -> next;
                         }
                         printf("%d\n",t -> info);
 }
 // Driver Function
 int main()
 {
     int k;
     printf("Enter the value of k:");
     scanf("%d",&k);
     add(2);
     add(4);
     add(6);
     add(8);
     add(10);
     add(12);
     add(14);
     add(16);
     printf("Given Linked List: \n");
     traverse(start);
     rotate(start,k);
     printf("Linked List after rotating: \n");
     traverse(start);
     return 0;
 } 

Output:

Rotate a Singly Linked List

Time Complexity: The time complexity of this method is O(n), where n is the total number of the nodes in the linked list.

Method-2:

In this method, we will first make the linked list circular and then move k-1 steps ahead form the starting or the head node. We will make it null and make the kth node as head of the linked list.

C program to rotate a linked list anti-clockwise by Method-2

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node *)malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // Function for rotating the linked list
 void rotate(struct node * head, int k)
 {
     int i;
     if (k == 0)
         return;
    struct node * curr = head;
 // For making the linked list circular
    while(curr -> next != NULL)
    {
             curr = curr -> next;
    }
    curr -> next = head;
    curr = head;
    for(i=1; i < k ; i++)
    {
             curr = curr -> next;
    }
    head = curr -> next;
    curr -> next = NULL;
    start = head;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d ->  ",t -> info);
                         t = t -> next;
                         }
                         printf("%d\n",t -> info);
 }
 // Driver Function
 int main()
 {
     int k;
     printf("Enter the value of k:");
     scanf("%d",&k);
     add(2);
     add(4);
     add(6);
     add(8);
     add(10);
     add(12);
     add(14);
     add(16);
     printf("Given Linked List: \n");
     traverse(start);
     rotate(start,k);
     printf("Linked List after rotating: \n");
     traverse(start);
     return 0;
 } 

Output: -

Rotate a Singly Linked List

Time Complexity: The time complexity of this method is O(n), where n is the total number of the nodes in the linked list.


Related Topics

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Find the fractional (n/kth) node in the linked list

Find the fractional (n/kth) node in the linked list In this problem, we have given a singly linked list and a number k. Here we need to find the (n/k)th element...

2 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Stack vs Heap Memory Allocation Data Structure

Difference Between Stack and Heap Memory Allocation Stack Memory Stack memory allocation is a way to use the system memory as a temporary storage of the data which is act like last-in-first-out...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Hashing and its Applications

Hashing Hashing refers to transforming plain text data in such a way that even if it is leaked for some reason, no one would be able to make sense of it....

6 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

FIFO approach

FIFO is first in first out approach. It is done for the list of elements in data structures where first element will be deleted after another element ia added to it Here,...

6 minutes read.

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

2 minutes read.