forked from Shubhamrawat5/open-source-contribution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplit a circular linked list into 2 halves
123 lines (101 loc) · 2.31 KB
/
Split a circular linked list into 2 halves
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
123
#include<stdio.h>
#include<stdlib.h>
/* structure for a Node */
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
void splitList(struct Node *head, struct Node **head1_ref, struct Node **head2_ref);
struct Node* newNode(int key)
{
struct Node *temp = new Node(key);
return temp;
}
/* Function to split a list (starting with head) into two lists.
head1_ref and head2_ref are references to head Nodes of
the two resultant linked lists */
void printList(struct Node *head)
{
struct Node *temp = head;
if(head != NULL)
{
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != head);
printf("\n");
}
}
/* Driver program to test above functions */
int main()
{
int t,n,i,x;
scanf("%d",&t);
while(t--)
{
struct Node *temp,*head = NULL;
struct Node *head1 = NULL;
struct Node *head2 = NULL;
scanf("%d",&n);
scanf("%d",&x);
head=new Node(x);
temp=head;
for(i=0;i<n-1;i++){
scanf("%d",&x);
temp->next=new Node(x);
temp=temp->next;
}
temp->next=head;
splitList(head, &head1, &head2);
// printf("\nFirst Circular Linked List");
printList(head1);
// printf("\nSecond Circular Linked List");
printList(head2);
}
return 0;
}
// } Driver Code Ends
/* The structure of linked list is the following
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
*/
// function which splits the circular linked list. head is pointer
// to head Node of given lined list. head1_ref1 and *head_ref2
// are pointers to head pointers of resultant two halves.
void splitList(Node *head, Node **head1_ref, Node **head2_ref)
{
if(head==NULL)
return;
Node *fast=head,*slow=head,*prev=NULL;
do{
prev=slow;
slow=slow->next;
fast=fast->next->next;
}while(fast!=head and fast->next!=head);
*head1_ref=head;
if(fast!=head){
*head2_ref=slow->next;
slow->next=*head1_ref;
fast->next=*head2_ref;
}
else{
*head2_ref=slow;
prev->next=*head1_ref;
while(slow->next!=fast){
slow=slow->next;
}
slow->next=*head2_ref;
}
}