-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
104 lines (80 loc) · 2.07 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
/*
* This is a linked list implementation of stack interface.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stack.h"
/* function to initialize a new stack variable */
void stackInit(stack *stkPtr)
{
stkPtr->top = NULL;
}
/* function to free the memory associated with the stack */
void stackDestroy(stack *stkPtr)
{
stkNode *temp, *temp2;
temp = stkPtr->top;
while (temp != NULL) {
temp2 = temp->next;
free(temp);
temp = temp2;
}
stkPtr->top = NULL;
}
/* function to add an element to the top of the stack */
void stackPush(stack *stkPtr, stkElement element)
{
stkNode *newNode;
/* allocate a new node to hold element pushed */
newNode = malloc(sizeof(stkNode));
if (newNode == NULL) {
fprintf(stderr, "Insufficient memory to push element on stack.\n");
exit(1);
}
/* put information in node */
newNode->element = element;
/* link new top node to old top node */
newNode->next = stkPtr->top;
/* make the new node the top node in stack */
stkPtr->top = newNode;
}
/* function that removes the element from the top of the stack */
stkElement stackPop(stack *stkPtr)
{
if (stackIsEmpty(stkPtr)) {
fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
exit(1);
}
stkElement element = (stkPtr->top)->element;
stkNode *temp = stkPtr->top;
stkPtr->top = (stkPtr->top)->next;
free(temp);
return element;
}
/* function that returns a true value if the stack is empty */
bool stackIsEmpty(stack *stkPtr)
{
return stkPtr->top == NULL;
}
/* function that returns the number of elements in the stack */
int stackLength(stack *stkPtr)
{
int count = 0;
stkNode *temp = stkPtr->top;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
/* function that returns the top element in the stack without removing it */
stkElement stackPeek(stack *stkPtr)
{
if (stackIsEmpty(stkPtr)) {
fprintf(stderr, "Stack is empty - can't peek.\n");
exit(1);
}
return (stkPtr->top)->element;
}