Stos

Opis problemu

Implementacja

1
#include <stdio.h>
2
#include <stdlib.h>
3
4
typedef struct Element {
5
int value;
6
struct Element *next;
7
} Element;
8
9
Element *top_el;
10
int el_count;
11
12
void init_stack() {
13
top_el = NULL;
14
el_count = 0;
15
}
16
17
void push(int value) {
18
Element *new_el = malloc(sizeof(Element));
19
new_el->value = value;
20
new_el->next = top_el;
21
top_el = new_el;
22
el_count++;
23
}
24
25
int top() {
26
if (top_el != NULL) {
27
return top_el->value;
28
}
29
}
30
31
void pop() {
32
if (top_el != NULL) {
33
Element *tmp = top_el->next;
34
free(top_el);
35
top_el = tmp;
36
el_count--;
37
return;
38
}
39
}
40
41
void clear() {
42
Element *tmp;
43
while (top_el != NULL) {
44
tmp = top_el->next;
45
free(top_el);
46
top_el = tmp;
47
}
48
}
49
50
int is_empty() { return top_el == NULL; }
51
52
int count() { return el_count; }
53
54
int main() {
55
int array[10] = {7, 3, 0, 1, 5, 2, 5, 19, 10, 5};
56
57
for (int i = 0; i < 10; i++) {
58
push(array[i]);
59
}
60
61
printf("Number of elements on the stack: %d\n", count());
62
63
while (!is_empty()) {
64
printf("Top element: %d\n", top());
65
pop();
66
}
67
68
clear();
69
70
return 0;
71
}