通过调试发现empty()函数执行了6次,而pop()和dequeue()分别执行了4次,
while(!S.empty()&&S.pop()==Q.dequeue());这条语句到底等价于哪条语句,
return (ptr==NULL);这条语句到底等价于哪条语句?
#include<iostream>
using namespace std;
struct list
{
int data; struct list *next;
};
class Stack
{
struct list *ptr;
public:
Stack()
{
ptr=NULL;
}
void push(int x)//进栈成员函数
{
struct list *newnode=new struct list;
newnode->data=x;
newnode->next=ptr;
ptr=newnode;
}
int pop()//出栈成员函数
{
//struct list *top;
int value;
value=ptr->data;
//top=ptr;
ptr=ptr->next;
//delete top;
return value;
}
int empty()
{
return (ptr==NULL);//为什么不能直接写成return NULL;?
}
};
class Queue
{
struct list *ptrf,*ptrb;
public:
Queue()
{
ptrf=ptrb=NULL;
}
void enqueue(int x)//进队成员函数
{
struct list *newnode=new struct list;
newnode->data=x;
newnode->next=NULL;
if(ptrb==NULL)
ptrf=ptrb=newnode;
else
{
ptrb->next=newnode;
ptrb=newnode;
}
}
int dequeue()//出队成员函数
{
//struct list *tmp;
int value;
value=ptrf->data;
//tmp=ptrf;
ptrf=ptrf->next;
//delete tmp;
return value;
}
};
void main()
{
Stack S;//定义一个栈对象
Queue Q;//定义一个队列对象
char ch;
cout<<"输入数据:";
while((ch=getchar())!='.')
{
S.push(ch);
Q.enqueue(ch);
}
while(!S.empty()&&S.pop()==Q.dequeue());//退栈和出队,比较是否相同
if(S.empty())
cout<<"输入的是回文数据."<<endl;
else
cout<<"输入的不是回文数据."<<endl;
system("pause");
}
粘错了
while( !S.empty() )
{
if( S.pop()!=Q.dequeue() ) break;
}
第1个问题:栈非空且出栈的数与出队列的数相同,则继续;直到条件不满足,则退出循环。正常情况下,应该将栈和队列排空。
第2个问题:是判断栈是否为空,只有栈是空时,ptr是NULL,返回1;非空时,ptr不是NULL,返回0.
==是判断是否等于
while( (!S.empty()) && (S.pop()==Q.dequeue()) );
return (ptr==NULL);//这句就是判断ptr是否等于NULL,结果是0或者1
while( !S.empty() )
{
if( S.pop()=Q.dequeue() ) break;
}