Repository navigation
Expand file tree
/
Copy pathAQ1.cpp
More file actions
67 lines (54 loc) · 1.31 KB
/
Copy pathAQ1.cpp
File metadata and controls
67 lines (54 loc) · 1.31 KB
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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
void splitCircularList(Node* head, Node*& head1, Node*& head2) {
if (!head || head->next == head) {
head1 = head;
head2 = nullptr;
return;
}
Node* slow = head;
Node* fast = head;
while (fast->next != head && fast->next->next != head) {
slow = slow->next;
fast = fast->next->next;
}
Node* mid = slow;
Node* tail = fast->next == head ? fast : fast->next;
head1 = head;
head2 = mid->next;
mid->next = head1;
tail->next = head2;
}
void printCircularList(Node* head) {
if (!head) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
cout << endl;
}
int main() {
Node* head = new Node(1);
Node* temp = head;
for (int i = 2; i <= 6; ++i) {
temp->next = new Node(i);
temp = temp->next;
}
temp->next = head;
Node *head1 = nullptr, *head2 = nullptr;
splitCircularList(head, head1, head2);
cout << "First half: ";
printCircularList(head1);
cout << "Second half: ";
printCircularList(head2);
return 0;
}