summaryrefslogtreecommitdiff
path: root/Algorithms/stack_static.c
diff options
context:
space:
mode:
Diffstat (limited to 'Algorithms/stack_static.c')
-rw-r--r--Algorithms/stack_static.c125
1 files changed, 125 insertions, 0 deletions
diff --git a/Algorithms/stack_static.c b/Algorithms/stack_static.c
new file mode 100644
index 0000000..299cf70
--- /dev/null
+++ b/Algorithms/stack_static.c
@@ -0,0 +1,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;
+}