您的位置:首页 > 编程语言 > C语言/C++

Stack-c++ template

2008-09-01 12:08 218 查看
//this is a link stack template by C
//It complied ok with dev-c and vc 6.0
//Fine name is Test.cpp
#include <cstdlib>
#include <iostream>
#include <cstring>
#include "StackList.h"
using namespace std;
int main(int argc, char *argv[])
{
 cout<<"Stack class template demo.../n";
//1.constrator Stack(),~Stack()
 StackList<int> int1,int2;
//2.IsEmpty(),IsFull()
 cout<<"int2.IsEmpty()="<<int2.IsEmpty()<<endl; //IsEmpty()
 cout<<"int2.IsFull()="<<int2.IsFull()<<endl; //IsFull() 
//3.top(),push(item),pop()
 int1.push(11);    //push(item)
 cout<<int1.top()<<" ";   //top()
 int1.push(22);
 cout<<int1.top()<<" ";
 int1.push(33);
 cout<<int1.top()<<" "<<endl;
 while(!int1.IsEmpty()){
  cout<<int1.top()<<" "; 
  int1.pop();    //pop()
 }
 system("Pause");
 return 0;
}
/*
*StackList.h
*this is a  StackList template by pointer link
*StackList ADT
*writer:chinanetboy ,QQ:44633197
*blog http://chinanetboy.bokee.com
*date:07/01/2008
*/
#ifndef H_StackList
#define H_StackList
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cassert>
using namespace std;
//StackList ADT list
template <class T>
struct NodeType{
 T info;
 NodeType<T> *link;
};
template <class T>
class StackList
{
public:
//1.constrator StackList(),~StackList()
 StackList();
 ~StackList();
//2.IsEmpty(),IsFull()
 bool IsEmpty();
 bool IsFull();
//3.top(),push(item),pop()
 T top();
 void push(const T& item);
 void pop();
//protected:
private:
 NodeType<T> *DataTop;
};
//1.constrator StackList(),~StackList()
 template <class T>
 StackList<T>::StackList(){
  DataTop=NULL;
 }
 template <class T>
 StackList<T>::~StackList(){
  NodeType<T> *temp;
  while(DataTop!=NULL){
   temp=DataTop;
   DataTop=DataTop->link;
   delete temp;
  }
 }
//2.IsEmpty(),IsFull()
 template <class T>
 bool StackList<T>::IsEmpty(){
  return(DataTop==NULL);
 }
 template <class T>
 bool StackList<T>::IsFull(){ 
  return false; 
 }
//3.top(),push(item),pop()
 template <class T>
 T StackList<T>::top(){
  assert(DataTop!=NULL);
  return DataTop->info;
 }
 template <class T>
 void StackList<T>::pop(){
  NodeType<T> *temp;
  if(DataTop!=NULL){
   temp=DataTop;
   DataTop=DataTop->link;
   delete temp;
  }
 }
 template <class T>
 void StackList<T>::push(const T& item){
  NodeType<T> *newnode;
  newnode=new NodeType<T>;
  assert(newnode!=NULL);
  newnode->info=item;
  newnode->link=DataTop;
  DataTop=newnode;  
 }
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class null system date blog