简体   繁体   中英

Why does the stack look like this?

It's made out of my own mind, not from the book, but from my own perspective, so why hasn't it been implemented according to the scenario?

Stack omitted empty and full due to code length

#include<stdio.h>

typedef struct stack{
    int key[100];
    int top;
}stack;

void init(stack* a){
    int i;
    for(i=0;i<100;i++){
        a->key[i]=0;
    }
    a->top = 0;
}

void push(stack* a, int num){
    a->key[a->top++] = num;
}

int pop(stack* a){
    return a->key[a->top--];
}

int main(void){
    stack a;
    init(&a);

    push(&a,10); push(&a,20); push(&a,30);
    printf("%d ",pop(&a)); printf("%d ",pop(&a)); printf("%d ",pop(&a));

    return 0;
}

I expect the output 30 20 10 but the actual output is 0 30 20

Your code actually does:

push(&a, 10); stack: key[0] = 10

push(&a, 20); stack: key[0] = 10 / key[1] = 20

push(&a, 20); stack: key[0] = 10 / key[1] = 20 / key[2] = 30

because in a->key[a->top++] = num; the part with a->top++ increments at the end. So at this point your top index is equal to 3. But when you pop your function, you should do --a->top to decrement first your index

pop(&a); stack: key[0] = 10 / key[1] = 20 / key[2] = 30 , your top index is now equal to 2.

pop(&a); stack: key[0] = 10 / key[1] = 20 , top = 1 your top index is now equal to 1.

pop(&a); stack: key[0] = 10 , your top index is now equal to 0.

Read What is the difference between int++ and ++int? if you want to have better explanations about i++ and ++i (or i-- and --i).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM