forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
136 lines (106 loc) · 2.52 KB
/
stack.c
File metadata and controls
136 lines (106 loc) · 2.52 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
author: Christian Bender
This is the implementation of the (generic) stack.
The implementation uses the dynamic memory management and the principle
of data hiding.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
/*
actual stack data structure
This pointer will pointing at the actual field (of void * pointers)
that represents the stack.
*/
void **array;
/* the current capacity of the stack */
int max = 10;
/* counter variable for counting the elements of the stack. */
int counter = 0;
/*
offset address
points at the top element of the stack.
*/
int offset = -1;
void initStack()
{
array = malloc(sizeof(void *) * max);
assert(array); /* tests whether pointer is assigned to memory. */
}
/*
grow: increases the stack by 10 elements.
This utility function isn't part of the public interface
*/
void grow()
{
max += 10; /* increases the capacity */
int i; // for the loop
void **tmp = malloc(sizeof(void *) * max);
/* copies the elements from the origin array in the new one. */
for (i = 0; i < max - 10; i++)
{
*(tmp + i) = *(array + i);
}
array = tmp; /* setups the new one as basis */
}
/* push: pushs the argument onto the stack */
void push(void *object)
{
assert(object); /* tests whether pointer isn't null */
if (counter < max)
{
offset++; /* increases the element-pointer */
/*
moves pointer by the offset address
pushs the object onto stack
*/
*(array + offset) = object;
/* increases the inner counter */
counter++;
}
else /* stack is full */
{
grow(); /* lets grow stack */
push(object); /* recursive call */
}
}
/*
pop: pops the top element of the stack from the stack.
*/
void *pop()
{
void *top = *(array + offset);
/* check pointers */
assert(top);
/* if use the pop-function, stack must not empty. */
assert(!isEmpty());
/* decreases the offset address for pointing of
the new top element */
offset--;
/* decreases the inner counter */
counter--;
return top;
}
/*
size: gets the number of elements of the stack.
*/
int size()
{
return counter;
}
/*
isEmpty(): returns 1 if stack is empty otherwise 0.
*/
int isEmpty()
{
return counter == 0;
}
/*
top: returns the top element from the stack without removing it.
*/
void *top()
{
/* offset address points to the top element */
return array[offset];
}