Stack-c++ template

来源:互联网 发布:小学信息技术编程ppt 编辑:程序博客网 时间:2024/05/23 18:05

//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

原创粉丝点击