﻿ C Program: Rotate a singly linked list to the right by k places

# 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
}
printf("\n");
}

// Function to rotate a linked list by a given number of positions
void rotate_List(struct Node** head_ref, int k) {
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

// 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
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:

What is the difficulty level of this exercise?

﻿