zoukankan      html  css  js  c++  java
  • 基于线性表的堆栈

    #ifndef IOSTREAM
    #include <iostream>
    #endif
    
    template<class T>
    class Stack
    {
    public:
    	Stack(int MaxSize=10);
    	~Stack();
    	bool IsEmpty()const{return top==0;}
    	bool IsFull()const{return top==MaxTop;}
    	T Top()const;
    	Stack<T>&Add(const T &x);
    	Stack<T>&Delete(T&x);
    
    	int GetStackSize()const;//确定堆栈的大小 
    private:
    	int top;
    	int MaxTop;
    	T *stack;//堆栈元素数组
    };
    
    //构造函数
    template<class T>
    Stack<T>::Stack(int MaxSize)
    {
    	MaxTop=MaxSize-1;
    	stack=new T [MaxSize];
    	top=-1;//因为top=0的时候等于已经有一个元素了,所以这里为-1
    }
    //析构函数
    template<class T>
    Stack<T>::~Stack()
    {
    	delete [] stack;
    }
    //弹出栈顶
    template<class T>
    T Stack<T>::Top()const
    {
    	if(IsEmpty()) throw OutOfBounds();
    	else
    	return stack[top];
    }
    //压入栈
    template<class T>
    Stack<T>&Stack<T>::Add(const T &x)
    {
    	if(IsFull())
    		throw NoMem();
    	top++;
    	stack[top]=x;
    	return *this;
    }
    
    //弹出栈
    template<class T>
    Stack<T>&Stack<T>::Delete(T&x)
    {
    	if((IsEmpty()))
    		throw OutOfBounds();
    	x=stack[top];
    	top--;
    	return *this;
    }
    
    //确定堆栈的大小 
    template<class T>
    int Stack<T>::GetStackSize()const
    {
    	if(IsEmpty())
    		throw OutOfBounds();
    	int len=top;
    	return ++len;
    }
    
  • 相关阅读:
    Java实现花朵数
    Java实现花朵数
    Java实现花朵数
    Java实现花朵数
    Java实现花朵数
    Java实现 黑洞数
    Java实现 黑洞数
    Java实现 黑洞数
    Could not create the view: An unexpected exception was thrown.问题解决
    让 SVN (TortoiseSVN)提交时忽略指定目录
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/1882334.html
Copyright © 2011-2022 走看看