-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperations.c
105 lines (92 loc) · 1.74 KB
/
operations.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
#include "monty.h"
/**
* is_number - checks if the toke is a number
* @token: token to validate
* Return: 1 if true, 0 otherwise
*/
int is_number(char *token)
{
char *n = token;
if (*n == '-')
n++;
while (*n)
{
if (!isdigit(*n))
return (0);
n++;
}
return (1);
}
/**
* push - push a element to the stack
* @stack: pointer to the head of the stack
* @line_number: line number of the op
* @n: value to push to the stack
* Return: 0 on success, -1 0n failure
*/
int push(stack_t **stack, unsigned int line_number, char *n)
{
if (!stack)
return (-1);
if (!is_number(n))
{
fprintf(stderr, "L%u: usage: push integer\n", line_number);
free_stack(*stack);
exit(EXIT_FAILURE);
}
if (add_node(stack, atoi(n)) == -1)
{
free_stack(*stack);
exit(EXIT_FAILURE);
}
return (0);
}
/**
* pall - prints all elements in a stack
* @stack: stack to print
* @line_number: line number
*/
void pall(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || !*stack)
return;
(void) line_number;
node = *stack;
while (node)
{
printf("%d\n", node->n);
node = node->next;
}
}
/**
* pint - prints the top of the stack
* @stack: stack to print
* @line_number: line number
*/
void pint(stack_t **stack, unsigned int line_number)
{
if (!stack || !*stack)
{
fprintf(stderr, "L%u: can't pint, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
printf("%d\n", (*stack)->n);
}
/**
* pop - removes the top of stack
* @stack: stack to pop
* @line_number: line number
*/
void pop(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || !*stack)
{
fprintf(stderr, "L%u: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
node = *stack;
*stack = (*stack)->next;
free(node);
}