繁体   English   中英

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

[英]Why does the stack look like this?

是我自己想出来的,不是书本上的,是我自己的角度,为什么不按照场景来实现呢?

由于代码长度,堆栈省略了空和满

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

我预计 output 30 20 10 但实际 output 是 0 30 20

您的代码实际上是:

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

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

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

因为在a->key[a->top++] = num; 最后带有a->top++的部分递增。 所以此时您的最高索引等于 3。但是当您弹出 function 时,您应该先执行--a->top以减少您的索引

pop(&a); 堆栈: key[0] = 10 / key[1] = 20 / key[2] = 30 ,您的顶部索引现在等于 2。

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

pop(&a); stack: key[0] = 10 ,您的顶部索引现在等于 0。

阅读int++ 和 ++int 有什么区别? 如果您想对 i++ 和 ++i(或 i-- 和 --i)有更好的解释。

暂无
暂无

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

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