c++栈

#include<iostream>
using namespace std;
struct Node
{
 char data;
 Node *next;
};
class Seqstack
{
public:
 Seqstack(){top=NULL;}
 ~Seqstack(){}
 void Push(char x);
 char Pop();
 char GetTop(); 
 int Empty();
 void Emptystack();
private:
 Node *top;
};
int Seqstack::Empty()//栈是否为空 
 {
  if(top==NULL)
   return 1;
  else
   return 0;
 }
char Seqstack::GetTop()//获取栈顶元素
{
  if(top!=NULL)
   return top->data;
  return 0;
}
void Seqstack::Push(char x)//添加节点 
{
 Node *s;
 s=new Node;s->data=x;
 s->next=top;top=s;
}
char Seqstack::Pop()//弹出栈顶 
{
 Node *p;
 char x;
 x=top->data;p=top;
 top=top->next;
 delete p;
 return x;
}
void Seqstack::Emptystack()//清空栈 
{
Node *p;
while(top!=NULL)
{
p=top;
top=top->next;
delete p;
}
}
int main()//主函数 
{
 Seqstack s;
 char m;
 char c;
 while(cin>>c&&c!='E')
 {
  if(c=='P')
  {
   cin>>m;
   s.Push(m);
  }
  if(c=='D')
  {
   if(!s.Empty())
   {
    cout<<s.Pop()<<endl;
   }
   else
   {
    cout<<"None"<<endl;
   }
  }
  if(c=='Y')
  {
   if(s.Empty()==1)
   {
    cout<<"Yes"<<endl;
   }
   else
    cout<<"No"<<endl;
  }
  if(c=='G')
  {
   if(!s.Empty())
   {
    cout<<s.GetTop()<<endl;
   }
  }
  if(c=='T')
  {
   if(!s.Empty())
   {
    s.Emptystack();
   }
  }
 }
 return 0;
}

猜你喜欢

转载自blog.csdn.net/perception952/article/details/78239044