forked from amritanand-py/cps02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCLL01 - Circular Linked List Insertions.cpp
113 lines (103 loc) · 2.43 KB
/
CLL01 - Circular Linked List Insertions.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
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define in(x) scanf(" %d", &x);
#define LinkedListNode LinkedListNode
typedef struct LinkedListNode LinkedListNode;
struct LinkedListNode {
int val;
struct LinkedListNode* next;
};
//-------------------- body of the code ------------------------
LinkedListNode* insertAtBeginning(LinkedListNode* tail, int val) {
LinkedListNode* temp= (LinkedListNode*)malloc(sizeof(LinkedListNode));
temp->val = val;
temp->next=NULL;
if(tail==NULL){
tail=temp;
tail->next=temp;
}
else{
temp->next = tail->next;
tail->next = temp;}
return tail;
}
LinkedListNode* insertAtEnd(LinkedListNode* tail, int val) {
LinkedListNode* temp= (LinkedListNode*)malloc(sizeof(LinkedListNode));
temp->val=val;
temp->next=NULL;
if(tail==NULL){
tail=temp;
tail->next=temp;
}
else{
temp->next = tail->next;
tail->next = temp;
tail=temp;}
return tail;
}
//-------------------- tail of the code ------------------------
int rng(int lim) {
if (lim == 0) return 0;
return rand()%lim;
}
int a[1005], sz = 0;
void insertt(int val, int pos) {
if (pos < 0) return;
if (pos > sz + 1) return;
sz += 1;
for (int i = sz; i > pos; i--)
a[i] = a[i - 1];
a[pos] = val;
}
void erasee(int pos) {
if (pos > sz) return;
if (pos < 1) return;
sz--;
for (int i = pos; i <= sz; i++)
a[i] = a[i + 1];
}
int check(LinkedListNode* tail) {
if (tail == NULL && sz == 0) return 1;
if (tail == NULL || sz == 0) return 0;
if (tail->val != a[sz]) return 0;
LinkedListNode* ii = tail->next;
for (int i = 1; i < sz; i++) {
if (ii == NULL) return 0;
if (a[i] != ii->val) return 0;
ii = ii->next;
}
return 1;
}
int main() {
srand(time(NULL));
int t, n; in(t); in(n);
while (t--) {
LinkedListNode* head = NULL;
sz = 0;
for (int i = 0; i < n; i++) {
int type = rng(4);
if (type == 0) {
int val = rng(1000);
head = insertAtBeginning(head, val);
insertt(val, 1);
if (!check(head)) {
printf("incorrect insertAtBeginning");
return 0;
}
}
if (type == 1) {
int val = rng(1000);
head = insertAtEnd(head, val);
insertt(val, sz + 1);
if (!check(head)) {
printf("incorrect insertAtEnd");
return 0;
}
}
}
}
printf("correct");
}