forked from wrightkhlebisol/monty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
131 lines (113 loc) · 2.28 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "monty.h"
/**
* check_num - checks if argument is a number or not, covers digits as well
* @num: number argument
*
* Return: 1 (number or digit), 0 (not a number nor digit)
*/
int check_num(char *num)
{
if (*num == '-')
{
num++;
}
if (*num == '\0')
return (0);
while (*num != '\0')
{
if (*num < '0' || *num > '9')
return (0);
num++;
}
return (1);
}
/**
* push - Put item at top of stack
* @head: pointer to the head node pointer
* @line_number: the line number read
*
* Return
*/
void push(stack_t **head, unsigned int line_number)
{
int num;
char *cmd_arg;
stack_t *temp = *head;
stack_t *new_node = malloc(sizeof(stack_t));
if (head == NULL)
{
fprintf(stderr, "Stack is not present\n");
exit(EXIT_FAILURE);
}
cmd_arg = strtok(NULL, " \t\r\n");
if (cmd_arg == NULL || check_num(cmd_arg) == 0)
{
fprintf(stderr, "L%u: usage: push integer\n", line_number);
exit(EXIT_FAILURE);
}
num = atoi(cmd_arg);
if (new_node == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
exit(EXIT_FAILURE);
}
new_node->n = num;
new_node->prev = NULL;
new_node->next = *head;
if (*head != NULL)
temp->prev = new_node;
*head = new_node;
}
/**
* pall - prints all elements present in the stack
* @head: pointer to the head node pointer
* @line_number: line number read
*
* Return: void
*/
void pall(stack_t **head, __attribute__((unused)) unsigned int line_number)
{
stack_t *temp = *head;
while (temp != NULL)
{
printf("%d\n", temp->n);
temp = temp->next;
}
}
/**
* pop - remove element from the top of the stack
* @head: pointer to head node pointer
* @line_number: the line number read
*
* Return: void
*/
void pop(stack_t **head, unsigned int line_number)
{
stack_t *temp = NULL;
if ((*head) == NULL)
{
fprintf(stderr, "L%d: can't pop an empty stack\n", line_number);
exit(EXIT_FAILURE);
}
temp = *head;
*head = temp->next;
temp->prev = NULL;
temp->next = NULL;
free(temp);
}
/**
* pint - prints element at the top of the stack
* @head: pointer to head node pointer
* @line_number: the line number read
*
* Return: void
*/
void pint(stack_t **head, unsigned int line_number)
{
if ((*head) == NULL)
{
fprintf(stderr, "L%d: can't pint, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
printf("%d\n", (*head)->n);
}