diff --git a/rotate_linkedlist.cpp b/rotate_linkedlist.cpp new file mode 100644 index 0000000..c3772f3 --- /dev/null +++ b/rotate_linkedlist.cpp @@ -0,0 +1,100 @@ +// filename: rotate_linkedlist.cpp +// Compile: g++ rotate_linkedlist.cpp -o rotate_linkedlist +// Run: ./rotate_linkedlist +// Author: mnvrohith +// Date: 22-10-2025 +// Description: +// A simple C++ implementation of rotating a singly linked list +// by k nodes. The linked list is implemented using a Node struct +// and LinkedList class with addFirst, display, and rotate methods. + + +#include +using namespace std; + +// Node structure for linked list +struct Node { + int data; + Node* next; +}; + +class LinkedList { + Node* head; // Pointer to the head of the list +public: + LinkedList() { head = nullptr; } + + // Add a new node at the beginning of the list + void addFirst(int x) { + Node* temp = new Node(); + temp->data = x; + temp->next = head; + head = temp; + } + + // Rotate the linked list by k nodes + void rotate(int k) { + if (head == nullptr || k <= 0) return; + + // Count total nodes + Node* temp = head; + int length = 1; + while (temp->next != nullptr) { + temp = temp->next; + length++; + } + + // Connect last node to head to make it circular + temp->next = head; + + // Adjust k if k > length + k = k % length; + if (k == 0) { + temp->next = nullptr; // break circular link + return; + } + + // Traverse to find the new tail (k-th node) + Node* newTail = head; + for (int i = 1; i < k; i++) { + newTail = newTail->next; + } + + // Set new head and break circular link + head = newTail->next; + newTail->next = nullptr; + } + + // Print the linked list + void display() { + Node* temp = head; + cout << "Linked List: "; + while (temp != nullptr) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "NULL" << endl; + } +}; + +int main() { + LinkedList ll; + + // Create sample linked list: 1->2->3->4->5->6 + ll.addFirst(6); + ll.addFirst(5); + ll.addFirst(4); + ll.addFirst(3); + ll.addFirst(2); + ll.addFirst(1); + + cout << "Original Linked List:" << endl; + ll.display(); + + int k = 2; + ll.rotate(k); + + cout << "Linked List after rotating by " << k << " nodes:" << endl; + ll.display(); + + return 0; +}