-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack_imple.c
98 lines (91 loc) · 1.68 KB
/
stack_imple.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
#include "monty.h"
/**
* push_element - Pushes a new element onto the stack.
* @top: Pointer to the top of the stack.
* @value: Value to be pushed onto the stack.
*
* Return: void
*/
void push_element(stack_t **top, unsigned int value)
{
stack_t *new_node = malloc(sizeof(stack_t));
if (!value)
{
free(new_node);
fprintf(stderr, "L%d: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
if (!new_node)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new_node->n = value;
new_node->next = NULL;
new_node->prev = NULL;
if (!(*top))
{
*top = new_node;
}
else
{
new_node->next = *top;
(*top)->prev = new_node;
(*top) = new_node;
}
}
/**
* print_stack - Prints all elements of the stack.
* @top: Pointer to the top of the stack.
* @value: Unused parameter.
*
* This function prints the elements of the stack.
*/
void print_stack(stack_t **top, unsigned int value)
{
stack_t *temp;
(void)value;
temp = *top;
while (temp)
{
printf("%d\n", temp->n);
temp = temp->next;
}
}
/**
* print_top - Prints the value at the top of the stack.
* @top: Pointer to the top of the stack.
* @value: Unused parameter (required by function pointer type).
*
*/
void print_top(stack_t **top, unsigned int value)
{
(void)value;
if (!(*top))
{
fprintf(stderr, "L%d: can't pint, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
else
{
printf("%d\n", (*top)->n);
}
}
/**
* free_stack - Frees a stack.
* @top: Pointer to the top of the stack.
*
* This function frees all the nodes in the stack.
*/
void free_stack(stack_t *top)
{
stack_t *temp;
if (!top)
return;
while (top)
{
temp = top;
top = top->next;
free(temp);
}
}