-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
89 lines (78 loc) · 1.69 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#define MAX_STACK_SIZE 256
typedef struct stack_entry
{
int value;
struct stack_entry *next;
}stack_entry;
int stack_count=0;
int push(stack_entry **stack, stack_entry *element);
stack_entry *pop(stack_entry **stack);
int main()
{
int i, ret=0;
stack_entry *stack=NULL;
stack_entry *element;
for (i=0; i<=255; i++)
{
element = (stack_entry*)malloc(sizeof(stack_entry));
element->value = i;
element->next = NULL;
ret = push(&stack, element);
if (ret)
{
printf("pushed onto stack %d\n",element->value);
}
}
for (i=0; i<=258; i++)
{
element = pop(&stack);
if (element == NULL)
{
printf("Stack is really empty!\n");
}
else
{
printf("poped from stack: %d\n", element->value);
}
}
return 0;
}
int push(stack_entry **stack, stack_entry *element)
{
if (stack_count==MAX_STACK_SIZE)
{
printf("Maximal stack size %d reached!\n", MAX_STACK_SIZE);
return -1;
}
else
{
element->next = *stack;
*stack = element;
stack_count++;
return 0;
}
}
stack_entry *pop(stack_entry **stack)
{
stack_entry *temp;
if (stack_count==0)
{
printf("Stack is empty!\n");
return NULL;
}
else
{
temp = *stack;
*stack = (*stack)->next;
stack_count--;
return temp;
}
}
int is_stack_empty(stack_entry *stack)
{
return stack_count?0:1;
}