-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-stack_operations.c
108 lines (93 loc) · 1.94 KB
/
01-stack_operations.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
#include "monty.h"
/**
* stack_push - to push new element in the stack
*
* @stack: refrance to stack to push onit
* @line_num: line num in Monty ByteCodes file.
*
* Return: void.
*/
void stack_push(stack_t **stack, unsigned int line_num)
{
char *arg = strtok(NULL, " \t\n");
stack_t *new_node;
if (arg == NULL || !is_integer(arg))
{
fprintf(stderr, "L%d: usage: push integer\n", line_num);
status = -1;
return;
}
new_node = malloc(sizeof(stack_t));
if (new_node == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
status = -1;
return;
}
new_node->n = atoi(arg);
new_node->prev = NULL;
new_node->next = *stack;
if (*stack != NULL)
(*stack)->prev = new_node;
*stack = new_node;
}
/**
* stack_pall - print elements in the stack.
*
* @stack: refrance to stack to print it.
* @line_num: line num in Monty ByteCodes file.
*
* Return: void.
*/
void stack_pall(stack_t **stack, unsigned int line_num)
{
stack_t *node;
if (stack == NULL || *stack == NULL)
return;
(void) line_num;
node = *stack;
while (node != NULL)
{
printf("%d\n", node->n);
node = node->next;
}
}
/**
* stack_pint - The opcode pint prints the value at the top of the stack.
*
* @stack: refrance to stack to print it.
* @line_num: line num in Monty ByteCodes file.
*
* Return: void.
*/
void stack_pint(stack_t **stack, unsigned int line_num)
{
if (stack == NULL || *stack == NULL)
{
fprintf(stderr, "L%d: can't pint, stack empty\n", line_num);
status = -1;
return;
}
printf("%d\n", (*stack)->n);
}
/**
* stack_pop - pop removes the top element of the stack.
*
* @stack: refrance to stack to print it.
* @line_num: line num in Monty ByteCodes file.
*
* Return: void.
*/
void stack_pop(stack_t **stack, unsigned int line_num)
{
stack_t *node;
if (stack == NULL || *stack == NULL)
{
fprintf(stderr, "L%d: can't pop an empty stack\n", line_num);
status = -1;
return;
}
node = *stack;
(*stack) = node->next;
free(node);
}