forked from tommydebisi/monty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations.c
137 lines (118 loc) · 2.47 KB
/
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
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
137
#include "monty.h"
/**
* push - adds node to top of stack
*
* @stack: first node in the list
* @nline: line currently on
*/
void push(stack_t **stack, unsigned int nline)
{
stack_t *new_node, *future = *stack;
int value;
if (!monty.arg || !_isdigit(monty.arg))
{
dprintf(STDERR_FILENO, "L%u: usage: push integer\n", nline);
exit(EXIT_FAILURE);
}
value = atoi(monty.arg);
new_node = malloc(sizeof(stack_t));
if (!new_node)
exit(EXIT_FAILURE);
new_node->n = value, new_node->next = NULL, new_node->prev = NULL;
if (!(*stack))
{
*stack = new_node;
return;
}
if (strcmp("stack", monty.operate) == 0) /* for (LIFO) */
{
(*stack)->prev = new_node;
new_node->next = *stack;
*stack = new_node;
return;
}
if (!(*stack)->next) /* for queue (FIFO) */
future->next = new_node, new_node->prev = future;
else
{
while (future->next)
future = future->next;
future->next = new_node, new_node->prev = future;
}
}
/**
* pall - print all value of list
*
* @stack: first node in the list
* @nline: line currently on
*/
void pall(stack_t **stack, unsigned int nline)
{
stack_t *future;
(void)nline;
future = *stack;
while (future)
{
printf("%d\n", future->n);
future = future->next;
}
}
/**
* pint - prints the value at the top of stack
*
* @stack: first node in the list
* @nline: line currently on
*/
void pint(stack_t **stack, unsigned int nline)
{
if (!*stack)
{
dprintf(STDERR_FILENO, "L%u: can't pint, stack empty\n", nline);
exit(EXIT_FAILURE);
}
printf("%d\n", (*stack)->n);
}
/**
* pop - removes the top element of the stack
*
* @stack: first node in the list
* @nline: line currently on
*/
void pop(stack_t **stack, unsigned int nline)
{
stack_t *future;
if (!*stack)
{
dprintf(STDERR_FILENO, "L%u: can't pop an empty stack\n", nline);
exit(EXIT_FAILURE);
}
future = *stack;
future = future->next;
free(*stack);
if (future)
future->prev = NULL;
*stack = future;
}
/**
* swap - swaps the top two elements of the stack
*
* @stack: first node in the list
* @nline: line currently on
*/
void swap(stack_t **stack, unsigned int nline)
{
stack_t *future;
future = *stack;
if (!future || !future->next)
{
dprintf(STDERR_FILENO, "L%u: can't swap, stack too short\n", nline);
exit(EXIT_FAILURE);
}
future->prev = future->next;
future->next->prev = NULL;
if (future->next->next)
future->next->next->prev = future;
future->next = future->next->next;
future->prev->next = future;
*stack = future->prev;
}