[英]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.