×

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

What Is Graph Data Structure

A graph is generally a set of vertices and edges or border that is mainly used to join these vertices. A graph is basically pictured as a cyclic tree in...

7 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.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

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.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 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.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.