개인 공부/코딩뉴비 챌린지
6주차 미션 - 1
240 • 사공이
2020. 8. 19. 07:01
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 | #include <stdio.h> #include <stdlib.h> typedef struct stack{ int top; int capacity; int* array; } Stack; Stack* createStack(int capacity) { Stack* stack = (Stack*)malloc(sizeof(Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int *)malloc(stack->capacity*sizeof(int)); return stack; } int isFull(Stack* stack) { return stack->top == stack->capacity-1; } int isEmpty(Stack* stack) { return stack->top == -1; } void push(Stack* stack, int item) { if (isFull(stack)) return; stack->array[++stack->top] = item; printf("%d pushed to stack\n", item); } int pop(Stack* stack) { int temp; // 마지막에 저장된 값을 저장하는 임시 변수 if (isEmpty(stack)) return -9999; temp = stack->array[stack->top]; --stack->top; // top을 감소시킴 return temp; } int peek(Stack* stack) { if (isEmpty(stack)) return; return stack->array[stack->top]; // 마지막에 저장된 값을 반환함 } int main() { Stack* stack = createStack(100); push(stack, 10); push(stack, 20); push(stack, 30); push(stack, 40); printf("%d pop from stack\n", pop(stack)); printf("%d pop from stack\n", pop(stack)); push(stack, 50); printf("%d pop from stack\n", pop(stack)); printf("%d pop from stack\n", pop(stack)); printf("%d pop from stack\n", pop(stack)); printf("%d pop from stack\n", pop(stack)); return 0; } | cs |