Repository navigation
Expand file tree
/
Copy pathstack_functions.c
More file actions
106 lines (92 loc) · 2 KB
/
Copy pathstack_functions.c
File metadata and controls
106 lines (92 loc) · 2 KB
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
#include "monty.h"
/**
* push - add new item to top of stack
* @stack: pointer to stack
* @line_number: line number of instruction
* @n: value of new item on stack
* Return: void, exit with -1 on failure
*/
void push(stack_t **stack, unsigned int line_number, char *n)
{
stack_t *new = NULL;
int i;
if (n == NULL)
{
printf("L%d: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
for (i = 0; n[i] != '\0'; i++)
{
if (n[0] == '-' && i == 0)
continue;
if (isdigit(n[i]) == 0)
{
printf("L%d: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
}
new = malloc(sizeof(stack_t));
if (new == NULL)
{
printf("Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new->n = atoi(n);
new->prev = NULL;
new->next = NULL;
if (*stack != NULL)
{
new->next = *stack;
(*stack)->prev = new;
}
*stack = new;
}
/**
* pop - remove item at the top of stack
* @stack: pointer to stack
* @line_number: line number of instruction
* Return: void, exit with -1 on failure
*/
void pop(stack_t **stack, unsigned int line_number)
{
stack_t *next;
if (stack == NULL || *stack == NULL)
{
printf("L%d: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
next = (*stack)->next; /* save next node's address */
free(*stack);
*stack = next; /* reassign next node to head */
}
/**
* swap - swaps the value of the top two elements on the stack
* @stack: pointer to stack
* @line_number: line number of instruction
* Return: void, exit with -1 on failure
*/
void swap(stack_t **stack, unsigned int line_number)
{
int temp_a;
int temp_b;
if (stack_length(stack) < 2)
{
printf("L%d: can't swap, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
temp_a = (*stack)->n;
temp_b = (*stack)->next->n;
(*stack)->n = temp_b;
(*stack)->next->n = temp_a;
}
/**
* nop - does nothing
* @stack: pointer to stack
* @line_number: line number of instruction
* Return: void
*/
void nop(stack_t **stack, unsigned int line_number)
{
(void)stack;
(void)line_number;
}