-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
114 lines (98 loc) · 2 KB
/
stack.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stack.h"
struct Stack
{
int* array;
unsigned int size;
int top;
};
Stack* stackCreate (int n)
{
if (n <= 0)
{
fprintf (stderr, "Invalid stack size %d.\n", n);
exit (EXIT_FAILURE);
}
Stack* out = malloc (sizeof (Stack));
if (out == NULL)
{
fprintf (stderr, "Memory allocation error.\n");
exit (EXIT_FAILURE);
}
int* outArr = malloc (n * sizeof *outArr);
if (outArr == NULL)
{
fprintf (stderr, "Memory allocation error.\n");
exit (EXIT_FAILURE);
}
out->array = outArr;
out->size = n;
out->top = -1;
return out;
}
void stackDelete (Stack* stack)
{
if (stack == NULL)
{
fprintf (stderr, "Empty memory.\n");
exit (EXIT_FAILURE);
}
free (stack->array);
free (stack);
}
void stackPush (Stack* stack, int val)
{
if (stack == NULL)
{
fprintf (stderr, "Empty memory.\n");
exit (EXIT_FAILURE);
}
stack->array[stack->top+1] = val;
stack->top++;
}
int stackPop (Stack* stack)
{
if (stack == NULL)
{
fprintf (stderr, "Empty memory.\n");
exit (EXIT_FAILURE);
}
if (stack->top + 1 >= stack->size)
{
fprintf (stderr, "Full stack.\n");
exit (EXIT_FAILURE);
}
if (stack->top < 0)
{
fprintf (stderr, "Memory error.\n");
exit (EXIT_FAILURE);
}
int out = stack->array[stack->top];
stack->array[stack->top] = 0;
stack->top--;
return out;
}
int stackPeek (Stack* stack)
{
if (stack == NULL)
{
fprintf (stderr, "Empty memory.\n");
exit (1);
}
if (stack->top == -1)
{
fprintf (stderr, "Memory error.\n");
exit (EXIT_FAILURE);
}
return stack->array[stack->top];
}
bool isEmpty (Stack* stack)
{
return stack->top == -1;
}
bool isFull (Stack* stack)
{
return stack->top + 1 >= stack->size;
}