This is a simple stack implementation question in C language

Asked 1 years ago, Updated 1 years ago, 50 views

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 should be stored in the stack 
        scanf_s ("%d",&num); // I don't think the push part is working well.
        stack[++top] = num; // other things are fine.
    }

    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);
    }
}

}

c stack

2022-09-21 20:52

1 Answers

stack[++top] = num;

Add 1 to top and stack[top] = num. That is stack[1] = num.

stack[top++] = num;

stack[top] = num and then add 1 to top. That is stack[0] = num.

I didn't look at the other codes properly, but this part stands out right away. If you're confused about this, you can clearly separate it and code it.

stack[top] = num;
top++;


2022-09-21 20:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.