stack.h

来自「这是一个对数学表达式求值的C++ class」· C头文件 代码 · 共 108 行

H
108
字号
#ifndef STACK_CLASS
#define STACK_CLASS


const int MaxStackSize = 1000;

template<class T>
class Stack
{
private:
	// private data members. stack array, and top
	T stacklist[MaxStackSize]; // array implementation
	int top;
	
public:
	// constructor; initialize the top
	Stack (void);

	// stack modification operations
	void Push (const T& item);
	T Pop (void);
	void Clear(void);

	// stack access
	T Peek (void) const;

	// stack test methods
	int IsEmpty(void) const;
	int IsFull(void) const;
};

// initialize stack top.
template<class T>
Stack<T>::Stack (void) : top(-1)
{}

// push item on the the stack
template<class T>
void Stack<T>::Push (const T& item)
{
    // if stacklist is full, terminate the program
    if (top == MaxStackSize - 1) {
		cerr << "Stack overflow!" << endl;
		exit(1);
    }

    // increment top and copy item to stacklist
    top++;
    stacklist[top] = item;
}

// pop the stack and return the top element
template<class T>
T Stack<T>::Pop (void)
{

    // if stack is empty, terminate the program
    if (top == -1) {
		cerr << "Attempt to pop an empty stack!" << endl;
		exit(1);
    }

    // record the top element
    T temp = stacklist[top];

    // decrement top and return former top element
    top--;
    return temp;
}

// return the value at the top of the stack
template<class T>
T Stack<T>::Peek (void) const
{
    // if the stack is empty, terminate the program
    if (top == -1) {
		cerr << "Attempt to peek at an empty stack!" << endl;
		exit(1);
    }
    return stacklist[top];
}


// test for an empty stack
template<class T>
inline int Stack<T>::IsEmpty(void) const
{
    // return the logical value top == -1
   return top == -1;
}

// test for a full stack
template<class T>
inline int Stack<T>::IsFull(void) const
{
   // test the position of top
   return top == MaxStackSize - 1;
}

// clear all items from the stack
template<class T>
inline void Stack<T>::Clear(void)
{
    top = -1;
}

#endif  // STACK_CLASS

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?