From a9e0a6fccaa7c8cddc36bbd98c67211c71b6aaf1 Mon Sep 17 00:00:00 2001 From: priyanshuanand166 <73073489+priyanshuanand166@users.noreply.github.com> Date: Thu, 13 Oct 2022 17:46:22 +0530 Subject: [PATCH] rotateALinkedlist.cpp Given a singly linked list, The task is to rotate the linked list counter-clockwise by k nodes. --- Linked List/rotateALinkedlist.cpp | 90 +++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Linked List/rotateALinkedlist.cpp diff --git a/Linked List/rotateALinkedlist.cpp b/Linked List/rotateALinkedlist.cpp new file mode 100644 index 0000000..c9d34d7 --- /dev/null +++ b/Linked List/rotateALinkedlist.cpp @@ -0,0 +1,90 @@ +// C++ program to rotate +// a linked list counter clock wise + +#include +using namespace std; + +/* Link list node */ +class Node { +public: + int data; + Node* next; +}; + +// This function rotates a linked list +// counter-clockwise and updates the +// head. The function assumes that k is +// smaller than size of linked list. +// It doesn't modify the list if +// k is greater than or equal to size +void rotate(Node** head_ref, int k) +{ + if (k == 0) + return; + + Node* current = *head_ref; + + int count = 1; + while (count < k && current != NULL) { + current = current->next; + count++; + } + + if (current == NULL) + return; + + Node* kthNode = current; + + while (current->next != NULL) + current = current->next; + + current->next = *head_ref; + + *head_ref = kthNode->next; + + kthNode->next = NULL; +} + +/* Function to push a node */ +void push(Node** head_ref, int new_data) +{ + /* allocate node */ + Node* new_node = new Node(); + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +/* Function to print linked list */ +void printList(Node* node) +{ + while (node != NULL) { + cout << node->data << " "; + node = node->next; + } +} + +int main() +{ + /* Start with the empty list */ + Node* head = NULL; + + // create a list 10->20->30->40->50->60 + for (int i = 60; i > 0; i -= 10) + push(&head, i); + + cout << "Given linked list \n"; + printList(head); + rotate(&head, 4); + + cout << "\nRotated Linked list \n"; + printList(head); + + return (0); +}