소프트웨어 개발/Algorithm

Array로 구현한 스택 (Stack)

Leo's notes 2019. 3. 1. 14:40

Example

#include <stdio.h>
#include <stdlib.h>

typedef struct _stack {
int *stack;
int top;
int size;
} Stack;

Stack *newStack(int size) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
int *arr = (int *)malloc(sizeof(int)*size);
stack->stack = arr;
stack->top = -1;
stack->size = size;
return stack;
}

void push(Stack *stack, int value) {
if(stack->size == stack->top) {
stack->stack = (int *)realloc(stack->stack, sizeof(int)*stack->size*2);
stack->size *= 2;
}
stack->stack[++(stack->top)] = value;
}

int pop(Stack *stack) {
return stack->stack[(stack->top)--];
}

int main() {

Stack *stack = newStack(2);
push(stack, 1);
push(stack, 2);
push(stack, 3);
push(stack, 4);
push(stack, 5);
printf("%d", pop(stack));
printf("%d", pop(stack));
printf("%d", pop(stack));
printf("%d", pop(stack));
printf("%d", pop(stack));

return 0;
}