-
Notifications
You must be signed in to change notification settings - Fork 0
/
circulara.cpp
109 lines (96 loc) · 2.39 KB
/
circulara.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
#include "utils.cpp"
struct nodLista {
Articol info;
nodLista* next;
nodLista* prev;
};
// adaugare articol in dublu inlantuita circulara
nodLista* adaugaArticol(nodLista* cap, int pos, Articol articol) {
nodLista* temp = (nodLista*)malloc(sizeof(nodLista));
temp->info = deepCopy(articol);
// nu avem cap
if (!cap) {
temp->next = temp;
temp->prev = temp;
return temp;
}
// inseram pe pozitia 0 (inceput)
if (pos == 0) {
temp->prev = cap;
temp->next = cap;
cap->prev = temp;
return temp;
}
// mergem prin lista pana cand ajungem la capat sau la pozitie
nodLista* curent = cap;
int i = 0;
while (curent->next != cap && pos != i) {
curent=curent->next; i++;
}
// verificam daca suntem la sfarsit
if (curent->next == cap) {
// inserare la sfarsit
temp->next = cap;
temp->prev = curent;
curent->next = temp;
cap->prev = temp;
} else {
// inserare pe pozitie
temp->next = curent;
temp->prev = curent->prev;
curent->prev = temp;
}
return cap;
}
nodLista* citesteArticole(nodLista* cap, char* f_name, int items) {
// citire din fisier
FILE* f = fopen(f_name,"r");
Articol articol;
int pos = INT_MAX; // inserare la sfarsit
for (int i=0; i<items; i++) {
articol = citesteArticol(f);
cap = adaugaArticol(cap, pos, articol);
}
fclose(f);
return cap;
}
int main() {
// lista articole
char f_name[] = "data-structures.in";
// citire numar de linii din fisier
int items = fileRecords(f_name);
nodLista* cap = NULL;
// citire articole in lista
cap = citesteArticole(cap, f_name, items);
// lista circulara, parcurgere si afisare in ambele sensuri
nodLista* curent = cap;
// parcurgem pana la mijloc
for (int i=0; i<items/2; i++) curent=curent->next;
nodLista* pos = curent;
printf("Lista circulara, parcurgere pe next:\n");
do {
afiseazaArticol(curent->info);
curent = curent->next;
if (curent == pos) break;
} while(true);
printf("Lista circulara, parcurgere pe prev:\n");
do {
afiseazaArticol(curent->info);
curent = curent->prev;
if (curent == pos) break;
} while(true);
// cleanup
curent = cap;
do {
free(curent->info.nume);
if (curent->next != cap) {
curent = curent->next;
free(curent->prev);
} else {
free(curent);
break;
}
} while(true);
printf("Sfarsit demonstratie.\n");
return 0;
}