[英]How can I correctly code my implementation of a stack in C?
我正在嘗試使用數組實現堆棧,到目前為止,這是我的代碼:
include <stdio.h>
int stack[100], top, n = 3;
void push();
void pop();
void show();
void main(){
top = -1;
int ch;
printf("1 = push, 2 = pop, 3 = display, 4 = exit \n");
printf("Enter a number: ");
scanf("%d", &ch);
do {
switch(ch){
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
printf("Exited the stack");
break;
default:
printf("Non existant number");
break;
}
} while (ch != 4);
}
void push(){
int value;
if (top > n){
printf("Stack Overflow");
} else {
printf("Add number to stack: ");
scanf("%d", value);
top++;
stack[top] = value;
}
}
void pop(){
if (top < 0){
printf("Stack Underflow");
} else {
top--;
}
}
void show(){
int i;
for (i = top; i >= 0; i--){
printf("%d", stack[i]);
}
}
但是,當我運行這段代碼並輸入 1,也就是push
一個值壓入堆棧時,我的代碼並沒有在添加值后中斷進程,而是不斷要求重復添加一個新值,直到發生堆棧溢出。
我認為在 switch case 中調用push
后添加break
語句會破壞 function 並要求再次輸入新數字,但在我當前的程序中,它沒有這樣做。
我應該在我的代碼中更改什么?
試試下面的代碼,
include <stdio.h>
int stack[100], top, n = 3;
void push();
void pop();
void show();
void main(){
top = -1;
int ch;
printf("1 = push, 2 = pop, 3 = display, 4 = exit \n");
printf("Enter a number: ");
scanf("%d", &ch);
do {
switch(ch){
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
printf("Exited the stack");
break;
default:
printf("Non existant number");
break;
}
printf("Enter a number: ");
scanf("%d", &ch);
} while (ch != 4);
}
void push(){
int value;
if (top == n){
printf("Stack Overflow");
} else {
printf("Add number to stack: ");
scanf("%d", &value);
top++;
stack[top] = value;
}
}
void pop(){
if (top < 0){
printf("Stack Underflow");
} else {
top--;
}
}
void show(){
int i;
for (i = top; i >= 0; i--){
printf("%d", stack[i]);
}
}
在這里,我更改了您的代碼中的幾個部分。 首先,我在 switch 語句之后添加了scanf
以從用戶端獲取號碼。 然后我改變了scanf("%d", &value);
在push
function 中。因為在您的代碼中沒有將值的地址傳遞給scanf
。 因此,值保持未初始化狀態。 最后,如果push
function 中的條件更改為檢查top
值是否等於n
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.