C언어 간단한 스택구현 질문입니당

조회수 611회

include

include

void main(){ int stack[1000]; int top; int n; int num = 0; top = 0; scanf_s("%d", &n);

for (int i = 0; i < n;i++) {
    char word[10]; 
    gets(word);

    if (strcmp(word, "push") == 0) { //push 1 하면 1이 스택에 저장되야 하는데 
        scanf_s(" %d",&num); // push 부분이 잘 안되는 것 같아요.
        stack[++top] = num;  //다른 것들은 괜찮은데..
    }

    else if (strcmp(word, "pop") == 0) {
        if (top <= 0)
            printf("no pop\n");
        else {
            printf("%d\n", stack[top - 1]);
            top--;
        }
    }
    else if (strcmp(word, "empty") == 0) {
        if (top <= 0)
            printf("1\n");
        else
            printf("0\n");
    }
    else if (strcmp(word, "top") == 0) {
        if (top <= 0)
            printf("-1\n");
        else printf("%d\n", stack[top]);
    }
    else if (strcmp(word, "size") == 0) {
        printf("%d\n", top);
    }
}

}

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • stack[++top] = num;
    

    top에 1을 더한 후 stack[top] = num을 합니다. 즉 stack[1] = num 이 됩니다.

    stack[top++] = num;
    

    stack[top] = num을 한 다음 top에 1을 더합니다. 즉 stack[0] = num 이 됩니다.

    다른 코드는 제대로 안봤는데 이 부분이 곧바로 눈에 띄네요. 이런 부분이 헷갈리면 명확하게 분리해서 코딩하시면 됩니다.

    stack[top] = num;
    top++;
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)