Stack类模板

             Stack类模板

#ifndef STACK_H

#define STACK_H

template <typename T>

class Stack

{

public:

      Stack( int = 10 ); //defaultconstructor (Stack size 10)

 

      // destructor

      ~Stack()

      {

           delete [] stackPtr; //deallocateinternal space for Stack

      } // end ~Stack destructor

 

      //determine whether Stack is full

      bool isFull() const

      {

           return top == size - 1;

      }

 

      //determine whether Stack is empty

      bool isEmpty() const

      {

           return top == -1;

      }

 

      bool push(constT&);// push an element onto the Stack

      bool pop( T&); // popan element off the Stack

 

private:

      int size; // # of elementsin the Stack

      int top; // location of thetop element (-1 means empty)

      T *stackPtr; // pointer to internal representation of the Stack

}; // end class template Stack

 

// constructor template

template <typename T>

Stack<T>::Stack( ints )

:size( s>0?s:0), // validatesize

top(-1), // Stack initiallyempty

stackPtr(new T[size]) //  allocate memoryfor elements

{

      // empty body

} // end Stack contructortemplate

 

//push element onto Stack

// if successful , return true;otherwise, return false

template <typename T>

bool Stack<T>::push(const T&pushValue)

{

      if(!isFull())

      {

           stackPtr[++top]=pushValue;

           return true;

      }

      return false;

}

 

// pop element off Stack

// if successful ,return true;otherwise,return false

template <typename T>

bool Stack<T>::pop(T&popValue)

{

      if(!isEmpty())

      {

           popValue=stackPtr[top--];// remove item from Stack

           return true; // pop successful

      }

      return false;

} // end function template pop

 

#endif

#include <iostream>

using namespace std;

 

#include "Stack.h"

 

int main()

{

   Stack<double> doubleStack( 5 );// size 5

 

   cout<<"Push elements onto doubleStack\n";

 

   double doubleValue = 1.1;

 

   while( doubleStack.push( doubleValue ))

   {

      cout<<doubleValue<<' ';

      doubleValue +=1.1;

   }

 

   cout<<"\nStack isfull.Cannot push" << doubleValue

      << "\n\nPoping elementsfrom doubleValue\n";

 

    while(doubleStack.pop( doubleValue ))

      cout<<doubleValue<< ' ';

 

   cout<<"\nStack isempty.Cannot pop\n";

 

   return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值