forked from TechVine/DSA--Hacktoberfest-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Splitting_Cirular_List.cpp
122 lines (100 loc) · 2.25 KB
/
Splitting_Cirular_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Program to split a circular linked list
// into two halves
#include <bits/stdc++.h>
using namespace std;
/* structure for a node */
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 there are even elements in list
then move fast_ptr */
if(fast_ptr->next->next == head)
fast_ptr = fast_ptr->next;
/* Set the head pointer of first half */
*head1_ref = head;
/* Set the head pointer of second half */
if(head->next != head)
*head2_ref = slow_ptr->next;
/* Make second half circular */
fast_ptr->next = slow_ptr->next;
/* Make first half circular */
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 linked list is not NULL then
set the next of last node */
if(*head_ref != NULL)
{
while(temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
/* Function to print nodes in
a given Circular linked list */
void printList(Node *head)
{
Node *temp = head;
if(head != NULL)
{
cout << endl;
do {
cout << temp->data << " ";
temp = temp->next;
} while(temp != head);
}
}
// Driver Code
int main()
{
int list_size, i;
/* Initialize lists as empty */
Node *head = NULL;
Node *head1 = NULL;
Node *head2 = NULL;
/* Created linked list will be 12->56->2->11 */
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
cout << "Original Circular Linked List";
printList(head);
/* Split the list */
splitList(head, &head1, &head2);
cout << "\nFirst Circular Linked List";
printList(head1);
cout << "\nSecond Circular Linked List";
printList(head2);
return 0;
}
//output:
// Original Circular Linked List
// 11 2 56 12
// First Circular Linked List
// 11 2
// Second Circular Linked List
// 56 12