我在这个程序的最后部分有问题。如何显示已弹出的元素?
我尝试更改循环,但不能..
#include<iostream.h>
typedef struct TINDANAN
{
int atas;
char senarai[4];
} tindanan;
void cipta(tindanan *t);
void push(tindanan *t);
void pop(tindanan *t);
int penuh(tindanan *t);
int kosong(tindanan *t);
void main()
{
int pilihan,jawapan,i;
tindanan t;
cipta(&t);
cout<<"\n1->Push\t\n 2->Pop \t\n 3-> Keluar \n pilihan =";
cin>>pilihan;
while(pilihan !=3)
{
switch (pilihan)
{
case 1: push(&t);
break;
case 2: pop(&t);
break;
default : cout<<"\nTidak Sah";
}
cout<<"\n1->Push\t\n 2->Pop \t\n 3-> Keluar \n pilihan =";
cin>>pilihan;
}
}
void cipta (tindanan *t)
{
t->atas =-1;
}
int penuh (tindanan *t)
{
if (t->atas ==3)
return (1);
else
return (0);
}
void push (tindanan *t)
{
int i;
char data;
if (penuh(t) ==1)
cout<<"\nTindanan Penuh\n";
else
{
cout<<"\nHuruf Character: ";
cin>>data;
t->atas++;
t->senarai[t->atas]=data;
cout<<"\nKandungan Timbunan :\nIndex | Data\n";
for(i=t->atas;i>-1;i--)
cout<<"| "<<i<< " | "<< t->senarai[i];
}
cout<<"\n";
}
int kosong (tindanan *t)
{
if (t->atas ==-1)
return (1);
else
return (0);
}
void pop (tindanan *t)
{
int i;
if(kosong(t) == 1)
cout<<"\nTindanan Kosong\n";
else
{
t->atas--;
cout<<"\nkandungan Timbunan :\nIndex | data\n";
for(i=t->atas;i>-1;i--)
cout<<" | "<<i<< " | "<<( t->senarai[i]);
cout<<"\nPop Item";
for(i=3;i>t->atas;i--)
cout<<"| "<<i<< " | "<< t->senarai[i];
}
}
抱歉,今年我只是学习c ++。
答案 0 :(得分:0)
让pop返回一个值并使此值等于您弹出的元素(在我看来这是您打印的值)。
答案 1 :(得分:0)
我不确定你在pop函数中的第二个循环到底是做什么的,但是这个修改过的pop应该显示弹出的值以及现有的内容。
void pop (tindanan *t)
{
int i;
if(kosong(t) == 1)
cout<<"\nTindanan Kosong\n";
else
{
cout<<"\nPop Item: " << (t->senarai[t->atas]);
t->atas--;
cout<<"\nkandungan Timbunan :\nIndex | data\n";
for(i = t->atas; i > -1; i--)
cout<<" | "<<i<< " | "<<( t->senarai[i]);
}
}
但总的来说,让pop返回项目是有意义的,因为这是通常的工作方式。但是再次推动通常也会推动该项目。
或者你可以像这样编写pop,它会返回弹出的项目然后你可以随意显示它。
char pop (tindanan *t)
{
char popped_item = -1;
int i;
if(kosong(t) == 1)
cout<<"\nTindanan Kosong\n";
else
{
cout<<"\nPop Item: " << (t->senarai[t->atas]);
popped_item = t->senarai[t->atas];
t->atas--;
cout<<"\nkandungan Timbunan :\nIndex | data\n";
for(i = t->atas; i > -1; i--)
cout<<" | "<<i<< " | "<<( t->senarai[i]);
}
return popped_item;
}