summaryrefslogtreecommitdiff
path: root/Algorithms/stack_static.c
blob: 299cf704e32c91887ad74378a1db62779667f94c (plain)
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
#include <stdio.h>
#include <stdbool.h>

#define STACK_SIZE 10

struct stack {
	int data[STACK_SIZE];
	int top;
};

bool stack_empty(struct stack *S)
{
	if (S->top)
		return false;
	else
		return true;
}

/*
 * Push an element to the top of the stack
 * - Return the element pushed in case of success
 * - Return 0 otherwise
 */
int stack_push(struct stack *S, int value)
{
	if (S->top == (STACK_SIZE - 1)) {
		printf("Stack full, avoiding overflow\n");
		return 0;
	}

	S->top++;
	S->data[S->top] = value;
	printf("Last element into stack: %d\n", S->data[S->top]);
	return value;
}

int stack_pop(struct stack *S)
{
	int ret = 0;

	if (S->top == -1) {
		printf("Stack empty, avoiding underflow\n");
		return 0;
	}

	ret = S->data[S->top];
	S->top--;
	return ret;
}

void print_stack(struct stack *S)
{
	int i;

	printf("Elements into stack: %d\n", S->top + 1);

	if (S->top < 0) {
		printf("Stack is empty\n");
		return;
	}

	printf("Pos | Val");
	for (i = 0; i <= S->top; i++)
		printf("\n %d  | %d", i, S->data[i]);
	printf(" <-- TOP\n");
}

void debug_stack(struct stack *S)
{
	int i;

	printf(" Stack Pointer is: %d\n", S->top);

	for (i = 0; i < STACK_SIZE; i++)
		printf("Position: %d - Value: %d\n", i, S->data[i]);
}


int main(void)
{
	/* Initialize the stack and all its elements to 0 */
	struct stack mystack;
	int i = STACK_SIZE;
	char cmd;

	mystack.top = -1; /* Stack is empty */
	for (i = 0; i < STACK_SIZE; i++)
		mystack.data[i] = 0;


	while (1) {
		int val = 0;
		printf("Select option (h for help): \n");
		scanf(" %c", &cmd);

		switch (cmd) {
			case 'a':
				printf(" Push value: ");
				scanf(" %d", &val);
				stack_push(&mystack, val);
				break;
			case 'o':
				printf("Popping stack\n");
				stack_pop(&mystack);
				break;
			case 'p':
				print_stack(&mystack);
				break;
			case 'd':
				debug_stack(&mystack);
				break;
			case 'q':
				return 0;
			default:
				printf("Invalid entry, please use:\n");
				printf("a - Push value to the stack\n");
				printf("o - Pop value from the stack\n");
				printf("p - Print the whole stack\n");
				printf("d - Debug stack, print all elements\n");
				printf("    into the stack array even beyond TOP\n");
				printf("q - Exit stack fun\n");
		}
	}
	return 0;
}