-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_func2.c
100 lines (94 loc) · 2.03 KB
/
stack_func2.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
#include "monty.h"
/**
* swap - swaps the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void swap(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't swap, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
current = current->next;
(*stack)->next = current->next;
(*stack)->prev = current;
current->next = (*stack);
current->prev = NULL;
(*stack) = current;
}
/**
* add - adds the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void add(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't add, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
(*stack) = current->next;
(*stack)->n += current->n;
(*stack)->prev = NULL;
free(current);
}
/**
* nop - an opcode that doesn't do anything
*
* @stack: stack
* @line_num: the line number
*/
void nop(stack_t **stack, unsigned int line_num)
{
(void) stack;
(void) line_num;
}
/**
* sub - subs the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void sub(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't sub, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
(*stack) = current->next;
(*stack)->n -= current->n;
(*stack)->prev = NULL;
free(current);
}
/**
* mul - mul the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void mul(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't mul, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
(*stack) = current->next;
(*stack)->n *= current->n;
(*stack)->prev = NULL;
free(current);
}