Basic knowledge of data structure (4)

Sequence table

3. stack

Stack is a special linear table. In terms of logical structure and storage structure, stack is no different from general linear table, but the allowed operations are limited. The insertion and deletion of stack are only allowed at one end of the end of the table. Therefore, stack is a linear table with limited operations.

(1) Abstract data type of stack and its implementation

All data elements in the stack are of the same type, which is called stack element. Inserting an element into the stack is called push, and deleting an element from the stack is called pop. The stack is also known as the LIFO.

One end of the stack that is inserted and deleted is called the top of the stack, and the other end is called the bottom of the stack. The bottom of the stack is fixed and the top of the stack is constantly changing. Stacks without stack elements are called empty stacks.

The top pointer always points to the last stack element. The array of stack elements is called stack space, which can be allocated statically or generated dynamically.  

The abstract data types of stacks represented by classes are as follows:

template <class T>
class Stack
{
	private:
	int top;          //Top pointer of stack
	T *elements;        //Array of stack elements
	int MaxSize;
	public:
	Stack(int MaxSize =defaultsize);        //Create stack space and generate an empty stack
	~Stack(void){delete[]elements;}         //Free stack space
	
	int Push(const T& item);
	
	T Pop(void);
	
	T GetTop(void);
	
	void MakeEmpty(void){top= -1;}
	
	boolean IsEmpty(void)const{return boolean(top== -1);}
	boolean IsFull(void)const{return boolean(top ==MaxSize-1);}
};
template<class T>
Stack<T>::Stack(int s)
{
	MaxSize = s;         
	elements = new T[MaxSize];           //Create stack space
	top = -1;                         //Generate an empty stack
}

Push():

template<class T>
int Stack<T>::Push(const T& item)    //Enter the stack. If the stack is not satisfied, the item will enter the stack and return 0. Otherwise, return - 1;
{
	if (!IsFull()){elements[++top]=item;return 0;}
	else return -1;
}

Pop(void):

template<class T>
Stack<T>::Pop(void)             //Stack out: if the stack is not empty, the top element of the stack will be out of the stack and return its value; otherwise, NULL will be returned.
{
	if (!IsEmpty())return elements[top--];
	else return NULL;
}

Read stack top element:

template<class T>
T Stack<T>::GetTop(void)
{                              //Read stack top. If the stack is not empty, the value of the top element of the stack is returned; otherwise, NULL is returned.
	if (!IsEmpty())return elements[top];
	else return NULL;
}

 

Posted by ManOnScooter on Mon, 30 Dec 2019 13:59:29 -0800