我为使用堆栈的程序创建的两个函数有问题.然而,我不能确定两个函数同时是否存在错误,因为它们是相互关联的.因此,当将数据添加到堆栈及其后续输出中时,我得到的输出并不完全正确.
input the 1 th element :1
input the 2 th element :2
input the 3 th element :3
所以如果输入是这样的,当我 Select 第三个选项来输出堆栈中的数据时,我得到了这样的输出
the elements in the stack are: 0
0
0
3
0
这是密码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 10
int i=1,choose;
/* i represents the number of inputted elements; choose represents the identifiers of the options in the menu.*/
int *sptr,*full,*empty;
int stack[MAXSIZE];
void push(void);
void pop(void);
void printInfo(void);
int main(){
sptr=stack; // sptr points to stack[0].
empty=stack; //empty points to stack[0]
full=stack+MAXSIZE-1; // full points to stack[9]
do{
printf("\n\t===============STACK ==============\n");
printf("\n\t 1.Push stack");
printf("\n\t 2.Pop stack");
printf("\n\t 3.Print elements of the stack");
printf("\n\t 4.Exit\n");
printf("\n\t Please choose[1-4] :");
scanf("%d",&choose);
switch(choose){
case 1:
push();
break;
case 2:
pop();
break;
case 3:
printInfo();
break;
case 4:
exit(0);
default:
printf("\n\n\t==================Input error=================");
break;
}
}while(1);
return 0;
}
void push(void){
sptr=stack+1; // sptr point to the next position of the array
if(sptr==full){
printf("\n\n ........The stack is full.......");
sptr--;
}else{
printf("input the %d th element : ",i++);
scanf("%d",sptr);
}
}
void pop(void){
if(sptr!=empty){
sptr--;
i--;
}else{
printf("\n\n\t\t ........the stack is empty.......");
i=1;
}
}
void printInfo(void){
int * temp;
temp=sptr;
printf("\n\n\t the elements in the stack are: ");
do{
if(temp!=empty){
for(i;i>=0;i--)
printf("%d\n",stack[i]);
temp--;
}else{
break;
}
}while(1);
printf("\n\n\t================END===============\n");
}
如有任何建议或批评,我将不胜感激.非常感谢.