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
73 changes: 73 additions & 0 deletions linked_list_problems/reverse_nodes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};

// Function to reverse k nodes
Node* reverseKGroup(Node* head, int k) {
Node* current = head;
Node* prev = nullptr;
Node* next = nullptr;
int count = 0;

// Count k nodes
Node* temp = head;
for (int i = 0; i < k; i++) {
if (!temp) return head; // Less than k nodes, return head
temp = temp->next;
}

// Reverse k nodes
count = 0;
current = head;
while (current != nullptr && count < k) {
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}

// Recursively call for the next part of the list
if (next != nullptr) {
head->next = reverseKGroup(next, k);
}

return prev;
}

// Function to print linked list
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}

// Driver code
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = new Node(6);
head->next->next->next->next->next->next = new Node(7);

int k = 3;

cout << "Original List: ";
printList(head);

head = reverseKGroup(head, k);

cout << "Modified List after reversing every " << k << " nodes: ";
printList(head);

return 0;
}