Program to Rotate a linked list by k nodes
Lets take linked list as 10->30->60->90->20->40 and we want to rotate it by k=4 nodes.That means we want to rotate from (k+1)th node.The final linked list after rotation will be like 20->40->10->30->60->90. The basic idea to do that is make the kth node as NULL and the last node will point to the head node.So here is the function of rotating the linked list by k nodes.
Program :
struct node
{
int data;
struct node* next;
};
// This function rotates a linked list counter-clockwise by k nodes and update head.
void rotate (struct node **head, int k)
{
if (k == 0)
return;
struct node* current = *head;
// current will either point to kth or NULL after this loop.
int count = 1;
while (count < k && current != NULL)
{
current = current->next;
count++;
}
// If current is NULL, k is greater than or equal to count
// of nodes in linked list.
if (current == NULL)
return;
// current points to kth node that is 90. Store it in a variable
struct node *knode = current;
// current will point to last node that is 40 after this loop
while (current->next != NULL)
current = current->next;
// Change next of last node to previous head 40->10
current->next = *head;
// Change head to (k+1)th node
// head is now changed to node 20
*head = kNode->next;
// change next of kth node to NULL that is 90
kNode->next = NULL;
}
Program :
struct node
{
int data;
struct node* next;
};
// This function rotates a linked list counter-clockwise by k nodes and update head.
void rotate (struct node **head, int k)
{
if (k == 0)
return;
struct node* current = *head;
// current will either point to kth or NULL after this loop.
int count = 1;
while (count < k && current != NULL)
{
current = current->next;
count++;
}
// If current is NULL, k is greater than or equal to count
// of nodes in linked list.
if (current == NULL)
return;
// current points to kth node that is 90. Store it in a variable
struct node *knode = current;
// current will point to last node that is 40 after this loop
while (current->next != NULL)
current = current->next;
// Change next of last node to previous head 40->10
current->next = *head;
// Change head to (k+1)th node
// head is now changed to node 20
*head = kNode->next;
// change next of kth node to NULL that is 90
kNode->next = NULL;
}
Comments
Post a Comment