-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack.c
103 lines (97 loc) · 2.13 KB
/
stack.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
#include "monty.h"
/**
* push_stack - Function that pushes an element to the stack
* @top: element at the top of the stack (head)
* @line_number: constant int value in the structure
* Return: void
*/
void push_stack(stack_t **top, unsigned int line_number)
{
stack_t *new_node;
if (top == NULL)
{
fprintf(stderr, "L%d: stack not found\n", line_number);
exit(EXIT_FAILURE);
}
new_node = malloc(sizeof(stack_t));
if (new_node == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new_node->next = *top;
new_node->prev = NULL;
new_node->n = take_num;
if (*top)
(*top)->prev = new_node;
*top = new_node;
}
/**
* pall_stack - Prints all values of stack, starting from top of stack.
* @top: element at the top of the stack (head)
* @line_number: constant int value in the structure
* Return: void
*/
void pall_stack(stack_t **top, unsigned int line_number)
{
stack_t *tmp = *top;
(void) line_number;
while (tmp != NULL)
{
printf("%d\n", tmp->n);
tmp = tmp->next;
}
}
/**
* pint_stack - Function that print the valueat top of stack
* @top: element at the top of the stack (head)
* @line_number: constant int value in the structure
* Return: void
*/
void pint_stack(stack_t **top, unsigned int line_number)
{
stack_t *tmp = *top;
if (tmp == NULL)
{
fprintf(stderr, "L%d: can't pint, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
else
printf("%d\n", tmp->n);
}
/**
* free_stack - Function that print the valueat top of stack
* @top: element at the top of the stack (head)
* Return: void
*/
void free_stack(stack_t **top)
{
stack_t *tmp;
if (top == NULL)
return;
tmp = *top;
while (tmp)
{
*top = tmp->next;
free(tmp);
tmp = *top;
}
}
/**
* pop_stack - Function that pop (delete) the value at top of stack
* @top: element at the top of the stack (head)
* @line_number: constant int value in the structure
* Return: void
*/
void pop_stack(stack_t **top, unsigned int line_number)
{
stack_t *tmp = *top;
if (top == NULL || *top == NULL)
{
fprintf(stderr, "L%u: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
tmp = tmp->next;
free(*top);
*top = tmp;
}