-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsplit-circular-list.cpp
94 lines (82 loc) · 2 KB
/
split-circular-list.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
83
84
85
86
87
88
89
90
91
92
93
94
// http://www.geeksforgeeks.org/split-a-circular-linked-list-into-two-halves/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
void splitCircular(Node *head);
void makeCircular(Node *head);
Node* addNode(Node *head, int data);
void printCircularList(Node *head);
void splitCircular(Node *head) {
if (head == NULL || head->next == NULL)
return;
Node *slow = head;
Node *fast = head;
while (fast->next != head && fast->next->next != head) {
fast = fast->next->next;
slow = slow->next;
}
// setting head of second list
Node *list2 = slow->next;
if (fast->next->next == head)
fast = fast->next;
fast->next = list2;
// setting head of first list
Node *list1 = head;
slow->next = list1;
cout<<endl<<"list 1: ";
printCircularList(list1);
cout<<endl<<"list 2: ";
printCircularList(list2);
}
void makeCircular(Node *head) {
if (head == NULL)
return;
Node *ptr = head;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = head;
}
Node* addNode(Node *head, int data) {
if (head == NULL)
return new Node(data);
Node *ptr = head;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = new Node(data);
return head;
}
void printCircularList(Node *head) {
if (head == NULL)
return;
Node *start = head;
while (head->next != start) {
cout<<head->data<<" ";
head = head->next;
}
cout<<head->data;
}
int main() {
Node *head = NULL;
head = addNode(head, 1);
head = addNode(head, 2);
head = addNode(head, 3);
head = addNode(head, 4);
head = addNode(head, 5);
head = addNode(head, 6);
head = addNode(head, 7);
makeCircular(head);
cout<<"original: ";
printCircularList(head);
cout<<endl<<"after splitting..";
splitCircular(head);
cout<<endl;
return 0;
}