1.栈的类模板
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Stack//用类模板定义存储多种数据类型的栈;
{
private:
T *elems;
int top;//栈顶位置
int tsize;//最大容量
public:
Stack(int _tsize):tsize(_tsize),top(0)
{
elems=new T[tsize];
cout<<"Stack is created!"<<endl;
}
void push(T e)//入栈,top==0要使用
{
if(full())
{
int oldsize=tsize;
tsize=10+oldsize;
T *tmp=new T[tsize];
if(!tmp)
{
cout<<"no"<<endl;
delete []tmp;
tmp=NULL;
}
int top2=0;
while(!isEmpty())
{
tmp[top2++]=elems[--top];
}
delete []elems;
elems=new T[tsize];
if(!elems)
{
cout<<"no"<<endl;
delete []elems;
elems=NULL;
}
top=0;
while(top2!=0)
{
elems[top++]=tmp[--top2];
}
delete []tmp;
elems[top++]=e;
}
else
elems[top++]=e;
}
T pop()//出栈
{
if(top>0)
{
return elems[--top];
}
}
T getTop()//获取栈顶元素
{
if(!isEmpty())
return elems[top-1];
}
bool isEmpty()//判断栈空
{
return top==0;
}
bool full()//判断栈满
{
return top==tsize;
}
void show()
{
while(!isEmpty())
{
cout<<getTop()<<" ";
pop();
}
cout<<endl;
}
~Stack()
{
delete []elems;
elems=NULL;
cout<<"Stack is erased!"<<endl;
}
};
int main()
{
Stack<int>iStack(100);
Stack<double> dStack(2);
Stack<char> sStack(2);
int num;
double re;
char ch;
for(int i=0;i<5;i++)
{
cin>>num;
iStack.push(num);
}
iStack.show();
for(int j=0;j<5;j++)
{
cin>>re;
dStack.push(re);
}
dStack.show();
for(int k=0;k<5;k++)
{
cin>>ch;
sStack.push(ch);
}
sStack.show();
// int Tsize;
// cin>>Tsize;
// Stack<int >iStack2(Tsize);
// for(int i=0;i<Tsize;i++)
// {
// cin>>num;
// iStack2.push(num);
// }
// iStack2.show();
return 0;
}
//1.所有new 都需要检查是否成功开辟空间
//2.重新开辟空间,不需要一下开辟过大
//3. T pop()//出栈
// {
// if(top>0)
// {
// return elems[top--];//返回出栈的值
// }
//
// }
2.实现撤销与恢复
#include<iostream>
#include<iomanip>
#include<string>
#include<stack>
using namespace std;
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
stack <string>Stack1,Stack2;
string x;
int cnt=0;
while(cin>>x)//在输入EOF后cin返回false使循环停止;
{
if(x=="1")
{
if(Stack1.empty())
{
cout<<"cannot be erased."<<endl;
continue;
}
Stack2.push(Stack1.top());
Stack1.pop();
cout<<Stack2.top()<<"is erased."<<endl;
}
else if(x=="2")
{
if(Stack2.empty())
{
cout<<"cannot be undone."<<endl;
continue;
}
Stack1.push(Stack2.top());
Stack2.pop();
cnt++;
cout<<Stack1.top()<<" is undone."<<endl;
}
else if(x=="3")
{
if(cnt==0)
{
cout<<"cannot be redone."<<endl;
continue;
}
cnt--;
Stack2.push(Stack1.top());
Stack1.pop();
cout<<Stack2.top()<<" is redone."<<endl;
}
else
{
Stack1.push(x);
}
}
return 0;
}