-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
52 lines (39 loc) · 719 Bytes
/
stack.c
File metadata and controls
52 lines (39 loc) · 719 Bytes
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
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack {
int data;
struct Stack *next;
} Stack;
int push(Stack **stack, int val) {
Stack *tmp;
if ((tmp = malloc(sizeof(*tmp))) == NULL) {
perror("Error");
exit(EXIT_FAILURE);
}
tmp->data = val;
tmp->next = *stack;
*stack = tmp;
return val;
}
int pop(Stack **stack) {
int ret = (*stack)->data;
Stack *tmp = (*stack)->next;
free(*stack);
*stack = tmp;
return ret;
}
int main() {
Stack *stack;
if ((stack = malloc(sizeof(*stack))) == NULL) {
perror("Error");
exit(EXIT_FAILURE);
}
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
while (stack->next != NULL) {
printf("%d\n", pop(&stack));
}
free(stack);
return 0;
}