Skip to content

Instantly share code, notes, and snippets.

@boki1
Created April 27, 2019 22:17
Show Gist options
  • Save boki1/c72fef84b171aad4f21b8336bcee8c9e to your computer and use it in GitHub Desktop.
Save boki1/c72fef84b171aad4f21b8336bcee8c9e to your computer and use it in GitHub Desktop.
Static stack implementation - School HW
// Static stack implementation
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 10
void show_stack(int *s, int stack_top)
{
if (stack_top == 0)
{
printf("Stack empty.\n");
return;
}
for (int i = 0; i < stack_top; ++i)
printf("%d ", s[i]);
printf("\n");
}
int push(int *s, int *stack_top, int el)
{
if (*stack_top + 1 >= STACK_SIZE)
return 0;
printf("Pushing %d to the stack...\n", el);
s[*stack_top] = el;
(*stack_top)++;
return 1;
}
int pop(int *s, int *stack_top, int *el)
{
if (*stack_top == 0)
return 0;
printf("Poping from the stack...\n");
*el = s[*stack_top];
s[(*stack_top)--] = 0;
return 1;
}
int main(int argc, char *argv[]) {
if (argc > 11)
{
printf("Too much elements for us. Limit is %d.\n", STACK_SIZE);
return 1;
}
int stack[STACK_SIZE];
for (int i = 0; i < STACK_SIZE; ++i) stack[i] = 0;
int top = 0;
bool no_error = true;
for (int i = 1; i < argc; ++i)
{
no_error = push(stack, &top, atoi(argv[i]));
if (!no_error)
printf("Error pushing %s to the stack.\n", argv[i]);
}
printf("Done pushing to the stack. Printing stack...\n");
show_stack(stack, top);
int el;
for (int i = 0; i < argc; ++i)
{
no_error = pop(stack, &top, &el);
if (!no_error)
printf("Error poping from the stack.\n");
}
printf("Done poping from stack. Printing stack...\n");
show_stack(stack, top);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment