Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions rotate_linkedlist.cpp
Original file line number Diff line number Diff line change
@@ -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 <iostream>
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;
}