-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_ops.c
129 lines (118 loc) · 2.46 KB
/
stack_ops.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "monty.h"
#include <stdio.h>
/**
* push - function that adds node at the end of a stack
* @stack: pointer to the head node of the stack
* @line: line number
* Return: nothing
*/
void push(stack_t **node, __attribute__((unused))unsigned int line)
{
stack_t *head = NULL;
stack_t *temp;
if (node == NULL || *node == NULL)
exit(EXIT_FAILURE);
if (head == NULL)
{
head = *node;
return;
}
temp = head;
head = *node;
head->next = temp;
temp->prev = head;
}
/**
* pall - function to print all elements ina stack
* @stack: pointer to the stack in the struct
* @line: line number
* Return: nothing
*/
void pall(stack_t **stack, unsigned int line)
{
stack_t *temp;
(void)line;
if (stack == NULL)
exit(EXIT_FAILURE);
temp = *stack;
while (temp != NULL)
{
printf("%d\n", temp->n);
temp = temp->next;
}
}
/**
* pop - function that removes the top element of a stack
* @stack: the pointer to the stack
* @line; the line number
* Return: nothing
*/
void pop(stack_t **stack, unsigned int line)
{
stack_t *temp;
(void)line;
if (stack == NULL && *stack == NULL)
{
fprintf(stderr, "L%d: the stack is empty\n", line);
exit(EXIT_FAILURE);
}
temp = *stack;
*stack = temp->next;
if (*stack != NULL)
(*stack)->prev = NULL;
free(temp);
}
/**
*swap - swaps the top two elements in the stack
*@stack: address of pointer to first stack element
*@line: line number
*
*/
void swap(stack_t **stack, unsigned int line)
{
stack_t *top, *tmp_top;
(void)line;
if (*stack == NULL || stack == NULL || (*stack)->next == NULL)
{
fprintf(stdout, "L%d: can't swap, stack too short\n", line);
exit(EXIT_FAILURE);
}
top = *stack;
tmp_top = top->next;
top->next = tmp_top->next;
if (tmp_top->next != NULL)
tmp_top->next->prev = top;
tmp_top->prev = top->prev;
if (top->prev != NULL)
top->prev->next = tmp_top;
top->prev = tmp_top;
tmp_top->next = top;
*stack = tmp_top;
}
/**
* nop - function that does nothing
* @stack: pointer to the top element of the stack
* @line: the line number
* Return: nothing
*/
void nop(stack_t **stack, unsigned int line)
{
(void)stack;
(void)line;
}
/**
* pint - prints the value at the top of the stack, followed by a new line.
* @stack: the stack
* @line_number: the current line number
*
* Return: void
*/
void pint(stack_t **stack, unsigned int line)
{
if (*stack == NULL)
{
fprintf(stdout, "L%d: can't pint, stack empty\n", line);
exit(EXIT_FAILURE);
}
printf("%d\n", (*stack)->n);
}