Skip to content

Instantly share code, notes, and snippets.

@LucasMagnum
Last active September 7, 2018 09:24
Show Gist options
  • Save LucasMagnum/6935b3ac4e7116537c66e8dd88174ef6 to your computer and use it in GitHub Desktop.
Save LucasMagnum/6935b3ac4e7116537c66e8dd88174ef6 to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int size;
int top;
int *items;
};
struct Stack* newStack(int size) {
struct Stack *stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->items = (int *)malloc(size * sizeof(int));
return stack;
}
void push(struct Stack *stack, int value) {
stack->items[++stack->top] = value;
}
bool isEmpty(struct Stack *stack) {
if (stack->top >= 0) {
return false;
}
return true;
}
int pop(struct Stack *stack) {
return stack->items[stack->top--];;
}
int peek(struct Stack *stack) {
return stack->items[stack->top];
}
int main() {
struct Stack *stack = newStack(5);
push(stack, 1);
pop(stack);
push(stack, 2);
push(stack, 3);
push(stack, 4);
push(stack, 5);
while (!isEmpty(stack)) {
printf("Value: %d\n", pop(stack));
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment