-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_ops_II.c
116 lines (98 loc) · 2.32 KB
/
stack_ops_II.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
#include "monty.h"
/**
* _swap - swaps the top two elements of the stack
* @stack: pointer to the top of the stack
* @line_number: line number of opcode occurs on
* Return: void
*/
void _swap(stack_t **stack, unsigned int line_number)
{
stack_t *temp = *stack;
int temp_n;
if (temp == NULL || temp->next == NULL)
{
fprintf(stderr, "L%d: can't swap, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
temp_n = temp->n;
temp->n = temp->next->n;
temp->next->n = temp_n;
}
/**
* _add - adds the top two elements of the stack
* @stack: pointer to the top of the stack
* @line_number: line number of opcode occurs on
*/
void _add(stack_t **stack, unsigned int line_number)
{
stack_t *temp = *stack;
int sum = 0, i = 0;
if (temp == NULL)
{
fprintf(stderr, "L%d: can't add, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
while (temp)
{
temp = temp->next;
i++;
}
if (stack == NULL || (*stack)->next == NULL || i < 2)
{
fprintf(stderr, "L%d: can't add, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
sum = (*stack)->n + (*stack)->next->n;
_pop(stack, line_number);
(*stack)->n = sum;
}
/**
* _nop - does nothing
* @stack: pointer to the top of the stack
* @line_number: line number of opcode occurs on
* Return: void
*/
void _nop(__attribute__((unused)) stack_t **stack,
__attribute__((unused)) unsigned int line_number)
{
;
}
/**
* _pchar - prints the ASCII value of the top element of the stack
* @stack: pointer to the top of the stack
* @line_number: line number of opcode occurs on
*/
void _pchar(stack_t **stack, unsigned int line_number)
{
int n;
if (stack == NULL || *stack == NULL)
{
fprintf(stderr, "L%d: can't pchar, stack empty\n", line_number);
free(var_global.buffer);
fclose(var_global.file);
free_dlistint(*stack);
exit(EXIT_FAILURE);
}
n = (*stack)->n;
if (n < 0 || n > 127)
{
fprintf(stderr, "L%d: can't pchar, value out of range\n", line_number);
free(var_global.buffer);
fclose(var_global.file);
free_dlistint(*stack);
exit(EXIT_FAILURE);
}
putchar(n);
putchar('\n');
}
/**
* _isalpha - checks if int c is a letter, lowercase or uppercase
* @c: int to be checked
* Return: 1 if c is a letter, lowercase or uppercase, 0 otherwise
*/
int _isalpha(int c)
{
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
return (1);
return (0);
}