-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
109 lines (97 loc) · 1.92 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
104
105
106
107
108
109
#include "monty.h"
/**
* add_node-front - adds node to the start of a stack (front)
* @stack: stack
* @n: number for new node
* Return: null or new node
*/
stack_t *add_node_front(stack_t **stack, const int n)
{
stack_t *new = malloc(sizeof(stack_t));
if (new == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
free(new);
return (NULL);
}
new->n = n;
new->next = *stack;
new->prev = NULL;
if(*stack != NULL)
(*stack)->prev = new;
*stack = new;
return (new);
}
/**
* add_node-queue - adds node to the start of a stack (queue)
* @stack: stack
* @n: number for new node
* Return: null or new node
*/
stack_t *add_node_queue(stack_t **stack, const int n)
{
stack_t *new = malloc(sizeof(stack_t));
stack_t *curr = *stack;
if (new == NULL)
{
free(new);
return (NULL);
}
new->n = n;
if (*stack == NULL)
{
new->next = NULL;
new->prev = NULL;
*stack = new;
return (new);
}
while (curr != NULL)
{
if (curr->next == NULL)
{
new->next = NULL;
new->prev = curr;
curr->next = new;
break;
}
curr = curr->next;
}
return (new);
}
/**
* print_stack - prints the stack
* @stack: pointer to head stack
* Return: size of stack
*/
size_t print_stack(const stack_t *stack)
{
size_t i = 0;
while (stack != NULL)
{
printf("%d\n", stack->n);
stack = stack->next;
i++;
}
return (i);
}
/**
* free-stack - frees a stack
* @stack: pointer to stack
* Return: no return
*/
void free_stack(stack_t *stack)
{
stack_t *curr = stack;
stack_t *next;
if (stack != NULL)
{
next = stack->next;
while (curr)
{
free(curr);
curr = next;
if (next != NULL)
next = next->next;
}
}
}