栈的类模板II

1.题目:

Problem Description

栈的类模板强化练习。

Input

输入数据有多组,每组占3行;第一行是一个字符串表示入栈元素的类型(Int,Double,Char)或中止符STOP,第2行首先输入整数n(实际入栈的元素个数),而后有n个对应类型的元素入栈,(若是栈满,则输出"full!!")第3行整数t表示出栈的个数。(栈的大小不大于100)

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;
}

posted @ 2013-06-07 13:51  忍住疼痛就不痛了  阅读(187)  评论(0)    收藏  举报