简体   繁体   English

为什么堆栈看起来像这样?

[英]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我预计 output 30 20 10 但实际 output 是 0 30 20

Your code actually does:您的代码实际上是:

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

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

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

because in a->key[a->top++] = num;因为在a->key[a->top++] = num; the part with a->top++ increments at the end.最后带有a->top++的部分递增。 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所以此时您的最高索引等于 3。但是当您弹出 function 时,您应该先执行--a->top以减少您的索引

pop(&a); stack: key[0] = 10 / key[1] = 20 / key[2] = 30 , your top index is now equal to 2.堆栈: key[0] = 10 / key[1] = 20 / key[2] = 30 ,您的顶部索引现在等于 2。

pop(&a); stack: key[0] = 10 / key[1] = 20 , top = 1 your top index is now equal to 1. stack: key[0] = 10 / key[1] = 20 , top = 1 你的顶部索引现在等于 1。

pop(&a); stack: key[0] = 10 , your top index is now equal to 0. stack: key[0] = 10 ,您的顶部索引现在等于 0。

Read What is the difference between int++ and ++int?阅读int++ 和 ++int 有什么区别? if you want to have better explanations about i++ and ++i (or i-- and --i).如果您想对 i++ 和 ++i(或 i-- 和 --i)有更好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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