-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopcode_funcs.c
142 lines (126 loc) · 2.26 KB
/
opcode_funcs.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
138
139
140
141
142
#include "monty.h"
/**
* push_func - function that pushes node to the stack
* @top: stack top
* @data: stack data
* Return: 0 if successful else -1
*/
int push_func(stack_t **top, int data)
{
stack_t *new;
new = malloc(sizeof(stack_t));
if (new != NULL)
{
new->prev = NULL;
new->n = data;
new->next = NULL;
new->next = *top;
if (*top != NULL)
(**top).prev = new;
*top = new;
}
else
{
fprintf(stderr, "Error: malloc failed\n");
return (-1);
}
return (0);
}
/**
* pall_func - function that prints the stack data
* @top: global stack variable
* @line_number: file line number
* Return: 0 if successful else do nothing
*/
int pall_func(
stack_t **top, __attribute__ ((unused)) unsigned int line_number)
{
stack_t *ptr;
if (*top != NULL)
{
ptr = *top;
while (ptr != NULL)
{
printf("%d\n", (*ptr).n);
ptr = (*ptr).next;
}
}
return (0);
}
/**
* pint_func - function that prints the top stack data
* @top: global stack variable
* @line_number: file line number
* Return: 0 if successful else -1
*/
int pint_func(stack_t **top, unsigned int line_number)
{
stack_t *ptr;
if (*top != NULL)
{
ptr = *top;
while (ptr != NULL)
{
printf("%d\n", (*ptr).n);
break;
}
}
else
{
fprintf(stderr, "L%d: can't pint, stack empty\n", line_number);
return (-1);
}
return (0);
}
/**
* pop_func - function to remove the top of the stack
* @top: stack top
* @line_number: file line number
* Return: 0 if successful else -1
*/
int pop_func(stack_t **top, unsigned int line_number)
{
stack_t *ptr;
if (*top != NULL)
{
ptr = *top;
while (ptr != NULL)
{
*top = (**top).next;
free(ptr);
break;
}
}
else
{
fprintf(stderr, "L%d: can't pop an empty stack\n", line_number);
return (-1);
}
return (0);
}
/**
* swap_func - function to swap the stack top value
* @top: stack top
* @line_number: file line number
* Return: 0 if successful else -1
*/
int swap_func(stack_t **top, unsigned int line_number)
{
int num_nodes;
stack_t *ptr;
int temp_value;
num_nodes = get_num_nodes(top);
if (num_nodes >= 2)
{
ptr = *top;
temp_value = ptr->n;
ptr->n = ptr->next->n;
ptr->next->n = temp_value;
}
else
{
fprintf(stderr, "L%d: can't swap, stack too short\n", line_number);
return (-1);
}
return (0);
}