forked from TechVine/DSA--Hacktoberfest-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_cll.cpp
98 lines (77 loc) · 1.5 KB
/
split_cll.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
95
96
//c++ code to split a circular linked list into two halves
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void splitList(Node *head, Node **head1_ref,
Node **head2_ref)
{
Node *slow_ptr = head;
Node *fast_ptr = head;
if(head == NULL)
return;
while(fast_ptr->next != head &&
fast_ptr->next->next != head)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
if(fast_ptr->next->next == head)
fast_ptr = fast_ptr->next;
*head1_ref = head;
if(head->next != head)
*head2_ref = slow_ptr->next;
fast_ptr->next = slow_ptr->next;
slow_ptr->next = head;
}
void push(Node **head_ref, int data)
{
Node *ptr1 = new Node();
Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
if(*head_ref != NULL)
{
while(temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1;
*head_ref = ptr1;
}
void printList(Node *head)
{
Node *temp = head;
if(head != NULL)
{
cout << endl;
do {
cout << temp->data << " ";
temp = temp->next;
} while(temp != head);
}
}
int main()
{
int list_size, i;
Node *head = NULL;
Node *head1 = NULL;
Node *head2 = NULL;
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
cout << "Original Circular Linked List";
printList(head);
splitList(head, &head1, &head2);
cout << "\nFirst Circular Linked List";
printList(head1);
cout << "\nSecond Circular Linked List";
printList(head2);
return 0;
}