-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_functions.c
More file actions
106 lines (101 loc) · 2.25 KB
/
stack_functions.c
File metadata and controls
106 lines (101 loc) · 2.25 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"
/**
* op_push - Pushes an element onto the stack
* @stack: doubly linked list representation of the stack
* @line_number: Line number of the instruction
* Return: void
*/
void op_push(stack_t **stack, unsigned int line_number)
{
stack_t *new_node;
(void) line_number;
new_node = malloc(sizeof(stack_t));
if (new_node == NULL)
{
printf("Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new_node->n = arg;
if (*stack == NULL)
new_node->next = NULL;
else
new_node->next = *stack;
new_node->prev = NULL;
*stack = new_node;
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
/**
* op_pop - Removes the top element of the stack.
* @stack: doubly linked list representation of the stack
* @line_number: Line number of the instruction
* Return: void
*/
void op_pop(stack_t **stack, unsigned int line_number)
{
stack_t *ptr;
if (*stack == NULL)
error_func(line_number, 3);
if ((*stack)->next == NULL)
{
free(*stack);
*stack = NULL;
}
else
{
ptr = (*stack)->next;
(*stack) = ptr;
ptr = ptr->prev;
(*stack)->prev = NULL;
free(ptr);
}
}
/**
* op_swap - swaps top two elements of the stack
* @stack: doubly linked list representation of the stack
* @line_number: Line number of the instruction
* Return: void
*/
void op_swap(stack_t **stack, unsigned int line_number)
{
stack_t *ptr;
if (*stack == NULL || (*stack)->next == NULL)
error_func(line_number, 4);
ptr = (*stack)->next;
(*stack)->prev = ptr;
(*stack)->next = ptr->next;
ptr->prev = NULL;
ptr->next = *stack;
*stack = ptr;
}
/**
* op_pall - Prints all elements of the stack
* @stack: doubly linked list representation of the stack
* @line_number: Line number of the instruction
* Return: void
*/
void op_pall(stack_t **stack, unsigned int line_number)
{
const stack_t *ptr;
(void) line_number;
if (stack == NULL)
exit(EXIT_FAILURE);
ptr = *stack;
while (ptr != NULL)
{
printf("%d\n", ptr->n);
ptr = ptr->next;
}
}
/**
* op_pint - Prints the value at the top of the stack
* @stack: doubly linked list representation of the stack
* @line_number: Line number of the instruction
* Return: void
*/
void op_pint(stack_t **stack, unsigned int line_number)
{
if (*stack == NULL)
error_func(line_number, 2);
printf("%d\n", (*stack)->n);
}