λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
🐍 Algorithm/μ•Œκ³ λ¦¬μ¦˜-Python

[μ•Œκ³ λ¦¬μ¦˜] Day1 - μŠ€νƒ

by Danna 2018. 8. 4.
728x90
728x90


01 문제




02 μ•Œκ³ λ¦¬μ¦˜


-      stack의 κΈ°λ³Έ κ΅¬μ‘°λŠ” ꡬ쑰체둜 μ •μ˜ν•˜μ˜€λ‹€. stack을 μ΄ˆκΈ°ν™”ν•˜λŠ” stack_init ν•¨μˆ˜μ™€ λͺ…령을 μœ„ν•œ push, pop, size, is_empty, top ν•¨μˆ˜ 생성

-      strcmp ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄ λ¬Έμžμ—΄μ„ 비ꡐ, λͺ…령을 κ΅¬λΆ„ν•œλ‹€.

-      push의 κ²½μš°μ—λŠ” μˆ«μžμ™€ ν•¨κ»˜ μž…λ ₯λ˜λ―€λ‘œ 띄어쓰기λ₯Ό ν† ν°μœΌλ‘œ μΈμ‹ν•˜μ—¬ push 와 n을 κ΅¬λΆ„ν•œ ν›„ n은 atoi(str -> int) ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄ μ •μˆ˜ λ³€μˆ˜μ— λŒ€μž…ν•œλ‹€.



03 μ½”λ“œ


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 10000
 
typedef struct array_stack
{
        int arr[LEN];
        int top;
}array_stack;
 
void stack_init(array_stack *pstack);
void push(array_stack *pstack, int x);
void pop(array_stack *pstack);
void size(array_stack *pstack);
void is_empty(array_stack *pstack);
void top(array_stack *pstack);
 
int main(void)
{
        int num;
        char inst[15] = { 0, };
        array_stack stack;
 
        stack_init(&stack);
        scanf("%d", &num);
        getchar();
        while (num--)
        {
                 gets(inst);
                 if (strncmp(inst, "push", 4) == 0)
                 {
                         int x;
                         char *pch;
                         pch = strtok(inst, " ");
                         pch = strtok(NULL, " ");
                         x = atoi(pch);
                         push(&stack, x);
                 }
                 else if (strcmp(inst, "pop") == 0)       pop(&stack);
                 else if (strcmp(inst, "size") == 0)      size(&stack);
                 else if (strcmp(inst, "empty") == 0)     is_empty(&stack);
                 else if (strcmp(inst, "top") == 0)       top(&stack);
        }
}
void stack_init(array_stack *pstack)
{
        pstack->top = -1;
}
void push(array_stack *pstack, int x)
{
        ++pstack->top;
        pstack->arr[pstack->top] = x;
}
void pop(array_stack *pstack)
{
        if (pstack->top == -1)
                 printf("-1\n");
        else
        {
                 printf("%d\n", pstack->arr[pstack->top]);
                 pstack->top--;
        }
}
void size(array_stack *pstack)
{
        printf("%d\n", pstack->top + 1);
}
void is_empty(array_stack *pstack)
{
        if (pstack->top == -1)
                 printf("1\n");
        else
                 printf("0\n");
}
void top(array_stack *pstack)
{
        if (pstack->top == -1)
                 printf("-1\n");
        else
                 printf("%d\n", pstack->arr[pstack->top]);
}



728x90
728x90