-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.c
103 lines (90 loc) · 1.54 KB
/
helpers.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"
/**
* free_stack - Frees all memory used by the stack
*
* @stack: the stack to free
*/
void free_stack(stack_t *stack)
{
stack_t *tmp;
while (stack)
{
tmp = stack->next;
free(stack);
stack = tmp;
}
}
/**
* strip_newline - remove newline from string
*
* @str: string to edit
*/
void strip_newline(char *str)
{
int i;
int len = strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == '\n')
{
str[i] = '\0';
break;
}
}
}
/**
* throw_usage_error - throw an error for wrong usage
*
* @line_number: line in file where error occurred
*/
void throw_usage_error(int line_number)
{
fprintf(stderr, "L%d: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
/**
* handle_stack_insert - insert a new node into the stack
*
* @stack: the stack to insert into
* @value_to_push_int: the value to insert
*/
void handle_stack_insert(stack_t **stack, int value_to_push_int)
{
stack_t *new_stack;
stack_t *head = *stack;
new_stack = malloc(sizeof(stack_t));
if (!new_stack)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new_stack->n = value_to_push_int;
if (strcmp(structure_mode, "queue") == 0)
{
new_stack->next = NULL;
if (!head)
{
new_stack->prev = NULL;
*stack = new_stack;
return;
}
while (head)
{
if (!head->next)
{
new_stack->prev = head;
head->next = new_stack;
break;
}
head = head->next;
}
}
else
{
if (head)
head->prev = new_stack;
new_stack->prev = NULL;
new_stack->next = head;
*stack = new_stack;
}
}