Stack : A special linear table that only allows inserting and deleting elements at a fixed end. One end of the data insertion and deletion operations is called the top of the stack, and the other end is called the bottom of the stack. The data elements in the stack comply with the LIFO (Last In First Out) principle.
Pushing the stack : The inserting operation of the stack is called pushing/pushing/pushing, and the data is put on the top of the stack.
Pop : The delete operation of the stack is called pop. The output data is at the top of the stack.
2. The specific implementation of the stack
2.1 Stacking
Ideas:
Before entering the stack, we must first determine whether the stack is full, and only when the stack is not full can new elements continue to be pushed onto the stack;
Because it is in the form of a sequence table, just add a new element at the end of the array;
Before popping the stack, you must determine whether there are any elements in the stack. Only with the element, you can pop the element;
Because the stack is first-in-last-out, you only need to pop the element at the last usedSize-1 position each time;
Then the size is reduced by 1;
//出栈public T pop(){
//空if(isEmpty()){
//return -1;thrownewRuntimeException("栈为空!");}
T ret =this.elem[this.usedSize-1];this.usedSize--;this.elem[usedSize]= null;return ret;}
2.3 Get the top element of the stack
Ideas:
Also first determine whether it is empty;
It is not empty, as long as it returns the element at the position of usedSize-1 (because the array index starts from 0);
//获取栈顶元素,但是不删除public T peek(){
//空if(isEmpty()){
//return -1;thrownewRuntimeException("栈为空!");}returnthis.elem[this.usedSize-1];}