堆栈的类模板

1.题目:

Problem Description

设计一个堆栈的类模板Stack,在模板中使用类型参数T表示栈中存放的数据,用非类型参数maxsize代表栈的大小(不大于100)。
class Stack
{
private:
T elems[maxsize];//elems数组用于存储栈的数据元素
int top;//栈顶的位置
public:
Stack(){top=0;}
void push(T e);//入栈
T pop();//出栈
bool empty();//判断栈是否为空
bool full();//判断栈是否满
};

Input

输入数据有多组,每组占3行;第1行首先输入整数n(实际入栈的元素个数),第2行有n个整数入栈,第3行为一个正整数t表示出栈的个数。

Output

依次输出出栈的数据,每个数据中间用空格隔开,若遇栈空,输出"empty!!"。

Sample Input

10  
1 2 3 4 5 6 7 8 9 10
5
5
12 3 4 6 8 
7

Sample Output

10 9 8 7 6
8 6 4 3 12 empty!! empty!!

2.参考代码:

#include <iostream>
using namespace std;

const int maxsize=100;

template <typename T>
class Stack
{
private:
 T elems[maxsize];
 int top;
public:
 Stack(){
  top=0;
 }
 void push(T e);
 T pop();
 bool empty();
 bool full();
};
template <typename T>
void Stack<T>::push(T e){
 if(!full())
  elems[top++]=e;
}
template <typename T>
T Stack<T>::pop(){
 if(!empty())
  return elems[--top];
}
template <typename T>
bool Stack<T>::empty(){
 if(top==0)
  return true;
 else
  return false;
}
template <typename T>
bool Stack<T>::full(){
 if(top==maxsize)
  return true;
 else
  return false;
}

int main()
{
 int n;
 int e;
 
 while(cin>>n)
 {
  Stack<int> s;
  while(n--)
  {
   cin>>e;
   s.push(e);
  }
  cin>>n;
  while(n--)
  {
   if(!s.empty())
    cout<<s.pop();
   else
    cout<<"empty!!";
   if(n)
    cout<<" ";//注意这里的格式是每两个数或字符串或数与字符串之间有空格
  }
  cout<<endl;
 }
 
 return 0;
}

后记:

      写这题主要是复习下模板还有简单的堆栈。

posted @ 2013-06-06 18:43  忍住疼痛就不痛了  阅读(302)  评论(0)    收藏  举报