-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonty_stack.c
114 lines (96 loc) · 1.98 KB
/
monty_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 "monty.h"
/* global variable make available in this file */
trackg_t essential;
/**
* stack_push - adds an element to the top of the stack
*
* @st: pointer to the pointer to the top most element/node
* of the stack
* @data: the data/element to be added
*
* Return: 1 representing failure, if malloc fail, 0 otherwise
*/
int stack_push(stack_t **st, int data)
{
stack_t *node;
node = malloc(sizeof(stack_t));
if (node == NULL)
return (1);
node->n = data;
node->next = NULL;
node->prev = (*st);
if (*st)
(*st)->next = node;
essential.stack_size++;
*st = node;
if (essential.stack_size == 1)
essential.st_bottom = node;
return (0);
}
/**
* stack_pop - removes the topmost element from the stack
*
* @st: pointer to the pointer to the top most element/node
* of the stack
*
* Return: nothing
*/
void stack_pop(stack_t **st)
{
stack_t *temp;
temp = (*st)->prev;
if (temp)
temp->next = NULL;
free(*st);
essential.stack_size--;
*st = temp;
if (essential.stack_size == 0)
essential.st_bottom = NULL;
}
/**
* stack_is_empty - checks whether the stack is empty
*
* @st: pointer to the pointer to the top most element/node
* of the stack
*
* Return: <true> if the stack is empty, <false> otherwise
*/
bool stack_is_empty(stack_t **st)
{
return ((!st || !(*st)) ? true : false);
}
/**
* stack_top - displays the topmost element of the stack
*
* @st: pointer to the pointer to the top most element/node
* of the stack
*
* Return: integer value of the element on top of the stack
*/
int stack_top(stack_t **st)
{
return ((*st)->n);
}
/**
* stack_free_all - release the memory allocated for all the
* elements (nodes) in the stack
*
* @st: pointer to pointer to the first element in the stack
*
* Return: nothing
*/
void stack_free_all(stack_t *st)
{
stack_t *temp;
if (!st)
return;
while (st)
{
temp = st->prev;
free(st);
st = temp;
}
essential.stack_size = 0;
essential.st_top = NULL;
essential.st_bottom = NULL;
}