-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
60 lines (47 loc) · 1.18 KB
/
stack.c
File metadata and controls
60 lines (47 loc) · 1.18 KB
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
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
struct Node *stackTop;
int empty() { return stackTop == NULL; }
void reset() {
while (!empty())
pop();
}
void push(int num) {
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = num;
newNode->next = stackTop;
stackTop = newNode;
}
int pop() {
struct Node *temp = stackTop;
stackTop = stackTop->next;
int toReturn = temp->data;
free(temp);
return toReturn;
}
void copy_to_array(int *array, size_t space) {
struct Node *current_node = stackTop;
for (size_t i = 0; i < space && current_node != NULL; ++i) {
array[i] = current_node->data;
current_node = current_node->next;
}
}
static int test_main() {
push(10);
printf("%d\n", pop());
for (int i = 0; i < 29; i++) {
push(i);
}
int array[29];
copy_to_array(array, 29);
for (int i = 0; i < 29; i++) {
printf("i = %d, pop() = %d\n", i, pop());
}
printf("The array contains: ");
for (int i = 0; i < 29; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}