Cの配列を使用してスタックですべての操作(プッシュ、ポップ、ピープ、更新、表示)を実行しようとしていshow()
ます。必要なすべての関数を呼び出した後、最後にを呼び出したときに正常に動作しています。しかし、操作の前に電話をかけるとshow()
、適切な結果が得られません。私は次のコードを使用しています:
int main()
{
push(1);
push(2);
push(3);
push(4);
push(6);
pop();
push(5);
show();//line 8
//push(7);//line 9
//pop();
//peep();
//update();
//show();//line 13
return;
}
void push(int num){//insert an item
if(top==MAXSIZE-1)
{
printf("Overflow condition");
return;
}
top++;
stack[top]=num;
//return;
}
void pop()//delete a item from top
{
int num;
if(top==-1)
{
printf("Underflow condition");
return;
}
num=stack[top];
top--;
//return;
}
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]);
}
//return;
}
void peep()//extract information
{
int loc,num;
printf("enter location:\n");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
num=stack[top-loc+1];
printf("\nItem at location %d is %d",loc,num);
}
}
void update(){//update information
int loc,item;
printf("enter new item:");
scanf("%d",&item);
printf("enter location:");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
stack[top-loc+1]=item;
printf("\nItem inserted");
}
}
ここで、を呼び出した後show()
、topは8行目で-1(空)を指すので、その後は次のようになります。
push()
上部ではなく位置1に挿入されます。pop()
アンダーフロー状態が表示されます。peep()
条件があれば更新が入ります。
では、一度呼び出した後、どうすればスタックの一番上の要素にトップを設定できますshow()
か?ありがとう。