栈的类模板II
1.题目:
Problem Description
Input
Output
每组数据输出一行!
依次输出出栈的数据,每个数据中间用空格隔开,若遇栈空,输出"empty!!"。
Sample Input
Int
10 1 2 3 4 5 6 7 8 9 10
5
Double
5 0.8 4.5 6.2 5.4 12.9
7
Char
8 g h s a f o i p
6
STOP
Sample Output
10 9 8 7 6
12.9 5.4 6.2 4.5 0.8 empty!! empty!!
p i o f a s
2.参考代码:#include <iostream>
#include <string.h>
#include <cstdio>
using namespace std;
const int maxsize=100;//注意这里栈的范围一定要是100不能超过更不能少了
template <class T>
class Stack
{
int top;
T elems[maxsize];
public:
Stack(){
top=0;
}
void push(T e);
T pop();
bool empty();
bool full();
};
template <class T>
void Stack<T>::push(T e){
if(!full())
elems[top++]=e;
else
cout<<"full!!"<<" ";
}
template <class T>
T Stack<T>::pop(){
if(!empty())
return elems[--top];
}
template <class T>
bool Stack<T>::empty(){
if(top==0)
return true;
else
return false;
}
template <class T>
bool Stack<T>::full(){
if(top==maxsize)
return true;
else
return false;
}
int main()
{
int n;
int a;
double b;
char c;
char s[200];
while(cin>>s)
{
if(!strcmp(s,"STOP"))
break;
else if(!strcmp(s,"Int"))
{
Stack<int> s1;
cin>>n;
while(n--)
{
cin>>a;
s1.push(a);
}
cin>>n;
while(n--)
{
if(!s1.empty())
cout<<s1.pop();
else
cout<<"empty!!";
if(n)
cout<<" ";
}
cout<<endl;
}
else if(!strcmp(s,"Double"))
{
Stack<double> s2;
cin>>n;
while(n--)
{
cin>>b;
s2.push(b);
}
cin>>n;
while(n--)
{
if(!s2.empty())
cout<<s2.pop();
else
cout<<"empty!!";
if(n)
cout<<" ";
}
cout<<endl;
}
else if(!strcmp(s,"Char"))
{
Stack<char> s3;
cin>>n;
getchar();
while(n--)
{
cin>>c;
s3.push(c);
}
cin>>n;
while(n--)
{
if(!s3.empty())
cout<<s3.pop();
else
cout<<"empty!!";
if(n)
cout<<" ";
}
cout<<endl;
}
}
return 0;
}

浙公网安备 33010602011771号