forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.c
57 lines (52 loc) · 1.08 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
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
void *data;
struct stack *next;
} Stack;
Stack *new_stack_node(void *data) {
Stack *new_node = (Stack*) malloc(sizeof(Stack));
if (new_node == NULL) {
return NULL;
}
new_node -> data = data;
new_node -> next = NULL;
return new_node;
}
int push(Stack **stack, void *data) {
Stack *new_node = new_stack_node(data);
if (new_node == NULL) {
return 0;
}
new_node -> next = *stack;
*stack = new_node;
return 1;
}
void *pop(Stack **stack) {
if (*stack == NULL) {
return NULL;
}
Stack *temp = *stack;
*stack = (*stack) -> next;
temp -> next = NULL;
void *data = temp -> data;
free(temp);
return data;
}
int main() {
int a = 5;
float b = 6.0;
char c[] = "Hello World!";
Stack *st = NULL;
push(&st, (void*) (&a));
push(&st, (void*) (&b));
push(&st, (void*) (c));
char *c_popped = (char*) pop(&st);
float b_popped = *((float*) pop(&st));
int a_popped = *((int*) pop(&st));
printf("%d %f %s\n", a_popped, b_popped, c_popped);
if (pop(&st) == NULL) {
printf("Unable to pop from empty stack\n");
}
return 0;
}