-
Notifications
You must be signed in to change notification settings - Fork 0
/
monty.c
102 lines (88 loc) · 1.72 KB
/
monty.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
#include "monty.h"
/**
* pall - Print all values on the stack
* @stack: pointer to head of stack
* @line_num: file's line number
* Return: Void
*/
void pall(stack_t **stack, unsigned int line_num)
{
stack_t *h = *stack;
(void)line_num;
while (h)
{
printf("%d\n", h->n);
h = h->next;
}
}
/**
* push - Pushes an element to the stack
* @stack: pointer to head of stack
* @line_num: file's line number
* @n: variable
* Return: address of new element
*/
void push(stack_t **stack, unsigned int line_num, int n)
{
stack_t *new, *h = *stack;
if (stack == NULL)
{
fprintf(stderr, "L%d: usage: push integer", line_num);
exit(EXIT_FAILURE);
}
new = malloc(sizeof(stack_t));
if (new == NULL)
exit(EXIT_FAILURE);
new->prev = NULL;
new->n = n;
new->next = *stack;
if (*stack)
h->prev = new;
*stack = new;
}
/**
* pop - Removes the top element of the stack
* @stack: pointer to head of stack
* @line_num: file's line number
* Return: Void
*/
void pop(stack_t **stack, unsigned int line_num)
{
stack_t *h = *stack;
if (!(*stack))
{
fprintf(stderr, "L%u: can't pop an empty stack\n", line_num);
exit(EXIT_FAILURE);
}
if (h)
{
*stack = (h)->next;
free(h);
}
}
/**
* swap - Swaps the top two elements of the stack
* @stack: pointer to head of stack
* @line_num: file's line number
* Return: Void
*/
void swap(stack_t **stack, unsigned int line_num)
{
stack_t *h = *stack, *ptr;
if ((*stack) == NULL || (*stack)->next == NULL)
{
fprintf(stderr, "L%u: can't swap, stack too short\n", line_num);
exit(EXIT_FAILURE);
}
if (h && h->next)
{
ptr = h->next;
if (ptr->next)
ptr->next->prev = h;
h->next = ptr->next;
ptr->prev = NULL;
ptr->next = h;
h->prev = ptr;
*stack = ptr;
}
}