C Exercises: Rotate a singly linked list to the right by k places
C Singly Linked List : Exercise-23 with Solution
Write a C program that rotates a singly linked list to the right by k places.
Sample Solution:
C Code:
#include<stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
// Function to display a linked list
void displayList(struct Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// Function to rotate a linked list by a given number of positions
void rotate_List(struct Node** head_ref, int k) {
struct Node* current = *head_ref;
int count = 1;
// find the last node of the linked list
while (current->next) {
current = current->next;
count++;
}
// set the next of the last node to the head
current->next = *head_ref;
// find the (count - k % count)th node from the beginning
for (int i = 0; i < count - k % count; i++) {
current = current->next;
}
// set the (count - k % count)th node as the new head
*head_ref = current->next;
current->next = NULL;
}
int main() {
struct Node* list1 = newNode(1);
list1->next = newNode(3);
list1->next->next = newNode(4);
list1->next->next->next = newNode(7);
list1->next->next->next->next = newNode(9);
printf("Original List: ");
displayList(list1);
int k = 1;
printf("\nRotate the said singly linked list to the right by %d places:\n", k);
rotate_List(&list1, k);
displayList(list1);
k = 2;
printf("\nRotate the said singly linked list to the right by %d places:\n", k);
rotate_List(&list1, k);
displayList(list1);
k = 4;
printf("\nRotate the said singly linked list to the right by %d places:\n", k);
rotate_List(&list1, k);
displayList(list1);
return 0;
}
Sample Output:
Original List: 1 3 4 7 9 Rotate the said singly linked list to the right by 1 places: 9 1 3 4 7 Rotate the said singly linked list to the right by 2 places: 4 7 9 1 3 Rotate the said singly linked list to the right by 4 places: 7 9 1 3 4
Flowchart :


C Programming Code Editor:
Previous: Add two numbers represented by linked lists.
Next: Change Kth node from beginning to end in a linked list.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join