c code to rotate linked list by k nodes.

  • clinked list
  • write a c code to rotate linked list by k nodes.

    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.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; void display(struct node *r) { printf("elements of list are : "); while (r) { printf("%d ---> ", r->data); r = r->next; } printf("NULL\n"); } struct node *create(struct node *head) { struct node *t, *p; int n; if (head == NULL) { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node : \n"); scanf("%d", &t->data); t->next = NULL; head = t; } if (head != NULL) { do { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node: \n"); scanf("%d", &t->data); t->next = NULL; p = head; while (p->next != NULL) { p = p->next; } p->next = t; printf("do you want to add more node press 1 for yes, 0 for no. "); scanf("%d", &n); } while (n); } return head; } struct node *rotate(struct node *head, int k){ int i=1; struct node *r=head; struct node *p,*hd; while(i!=k){ r=r->next; i++; } p=r; hd=r->next; r=r->next; p->next=NULL; while(r->next!=NULL){ r=r->next; } r->next=head; return hd; } int main() { int i,k; struct node *head = NULL; printf("####enter the data of linked_list.####\n"); head = create(head); display(head); printf("enter value of k\n"); scanf("%d",&k); head = rotate(head,k); display(head); return 0; }