Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in linked list.
Algorithm: To rotate the linked list, we need to change next of kth node to NULL, next of last node to previous head node, and finally change head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node and last node. Traverse the list from beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till end and store pointer to last node also. Finally, change pointers as stated above.
// https://www.geeksforgeeks.org/rotate-a-linked-list/
#include <iostream>
#include <list>
using namespace std;
struct linked_list {
int data;
struct linked_list *next;
};
typedef struct linked_list node;
void print (node *n) {
while (n) {
cout<< n->data<< "->";
n = n->next;
}
cout<< "NULL";
return;
}
void insert(node **headref, int n) {
node* last = *headref;
node *temp=new node;
temp->data = n;
temp->next=NULL;
if (last == NULL) {
*headref = temp;
return;
}
while (last->next)
last = last->next;
last->next = temp;
return;
}
void rotate(node **headref, int k) {
node *tempk = *headref;
while (k>1){
tempk = tempk->next;
k--;
}
if (tempk == NULL)
return;
node *last = tempk;
while (last->next)
last = last->next;
last->next = *headref;
*headref = tempk->next;
tempk->next = NULL;
}
int main() {
int n;
node *head=NULL;
while (true) {
cout<< "Enter the number: ";
cin>>n;
if (n==-9)
break;
else
insert(&head,n);
}
cout<< "Enter k: ";
cin>>n;
cout<< "Before rotating: ";
print(head);
rotate(&head, n);
cout<< "\nAfter rotating: ";
print(head);
}