forked from Pheonix-001/Hacktoberfest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse a doubly linked list in groups of given size.cpp
82 lines (64 loc) · 1.44 KB
/
Reverse a doubly linked list in groups of given size.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next, *prev;
};
Node* getNode(int data)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = new_node->prev = NULL;
return new_node;
}
void push(Node** head_ref, Node* new_node)
{
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
Node* revListInGroupOfGivenSize(Node* head, int k)
{
Node *current = head;
Node* next = NULL;
Node* newHead = NULL;
int count = 0;
while (current != NULL && count < k)
{
next = current->next;
push(&newHead, current);
current = next;
count++;
}
if (next != NULL)
{
head->next = revListInGroupOfGivenSize(next, k);
head->next->prev = head;
}
newHead->prev = NULL;
return newHead;
}
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
int main()
{
Node* head = NULL;
push(&head, getNode(2));
push(&head, getNode(4));
push(&head, getNode(8));
push(&head, getNode(10));
int k = 2;
cout << "Original list: ";
printList(head);
head = revListInGroupOfGivenSize(head, k);
cout << "\nModified list: ";
printList(head);
return 0;
}