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
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++;
© 2024 OneMinuteCode. All rights reserved.