-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpush.c
92 lines (82 loc) · 1.64 KB
/
push.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
#include "monty.h"
/**
* push - prints all the values on the stack, starting
* from the top of the stack
* @stack: a pointer to the stack struct
* @line_number: the line number of each line in the file
*/
void push(stack_t **stack, unsigned int line_number)
{
if (file_ptr->num_tokens <= 1 || !(is_digit_(file_ptr->tokens[1])))
{
fprintf(stderr, "L%d: usage: push integer\n", line_number);
fclose_file();
free_tokens();
free_file_ptr();
exit(EXIT_FAILURE);
}
/*printf("in push DEBUG: Token[1]: %s\n", file_ptr->tokens[1]);*/
*stack = malloc(sizeof(stack_t));
if (*stack == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
fclose_file();
free_tokens();
free_file_ptr();
exit(EXIT_FAILURE);
}
(*stack)->next = (*stack)->prev = NULL;
(*stack)->n = (int) atoi(file_ptr->tokens[1]);
if (file_ptr->head != NULL)
{
(*stack)->next = file_ptr->head;
file_ptr->head->prev = *stack;
}
file_ptr->head = *stack;
}
/**
* is_digit_ - checks if a string is a digit
* @str: the string o check
* Return: 0 on success
*/
int is_digit_(char *str)
{
int i = 0;
while (str[i] != '\0')
{
if (i == 0 && str[i] == '-' && str[i + 1])
{
i++;
continue;
}
if (str[i] < '0' || str[i] > '9')
{
return (0);
}
i++;
}
return (1);
}
/**
* free_stack - handles the free of all the stacks created
* @head: a pointer to the head of the node
*/
void free_stack(stack_t *head)
{
if (head == NULL)
return;
if (head->next != NULL)
{
free_stack(head->next);
}
free(head);
}
/**
* free_head - frees the head pointer
*/
void free_head(void)
{
if (file_ptr->head)
free_stack(file_ptr->head);
file_ptr->head = NULL;
}