Reverse A Linked List in Group of a Given Size
Reverse a Linked List in groups of a given size
https://practice.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1
Space complexity: O(0);
Time complexity: O(n);
struct node *reverse(struct node *head, int k)
{
int n = k;
if (head == 0 || head->next == 0) return head;
struct node *tempHead = head->next;
head->next = 0;
struct node *tail = head;// head will become tail later
//reverse K element
while (tempHead != 0 && n>1) {
struct node *temp = tempHead;
tempHead = tempHead->next;
temp->next = head;
head = temp;
n--;
}
tail->next = reverse(tempHead, k);
return head;
}
#include<iostream>
#include<string>
using namespace std;
class node {
public:
int data;
node *next;
node(int d) {
data = d;
next = 0;
}
};
class linkedList{
private:
node *head;
public:
linkedList() {
head = 0;
}
void addFirst(int d) {
node *newNode = new node(d);
if (head == 0)
head = newNode;
else {
newNode->next = head;
head = newNode;
}
}
void reverse(int k) {
head=reverse(head, k);
}
struct node *reverse(struct node *head, int k)
{
int n = k;
if (head == 0 || head->next == 0) return head;
struct node *tempHead = head->next;
head->next = 0;
struct node *tail = head;// head will become tail later
//reverse K element
while (tempHead != 0 && n>1) {
struct node *temp = tempHead;
tempHead = tempHead->next;
temp->next = head;
head = temp;
n--;
}
tail->next = reverse(tempHead, k);
return head;
}
void print() {
node *temp = head;
while (temp != 0) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
int n[] = { 1,2 ,3};
//int n[] = { 1,2,2,4,5,6,7,8,9};
linkedList a;
for (int i = 2;i >=0;i--) {
a.addFirst(n[i]);
}
a.print();
a.reverse(4);
a.print();
system("PAUSE");
return 0;
}
// by Y Nguyen
Comments
Post a Comment