What is stack:
Stack is a simple data structure used to store data, which is similar to linked list or sequence table (collectively referred to as linear table). The biggest difference between stack and linear table is the operation of data access. We can think that stack is a special linear table, and its insertion and deletion operations are only allowed at one end of linear table. Generally speaking, the one end that is allowed to be operated is called the top of stack At the same time, the operation of inserting elements is called push, and the operation of deleting elements is called pop. If there is no element in the stack, it is called empty stack. The stack is implemented in java by array,
The structure of the stack is as follows:
The stack can only access the elements from the top of the stack, and the elements that enter first come out later.
Various operations of stack and its code implementation
class stack{
int top;
int []elem;
public stack(){
this(10);
}
public stack(int size) {
this.elem=new int [size];
this.top=0;
// TODO Auto-generated constructor stub
}
//Is the stack full
public boolean isfull()
{
if(this.top==this.elem.length){
return true;
}
return false;
}
//Push
public boolean rush(int val){
if((isfull())){
return false;
}
this.elem[top]=val;
this.top=top+1;
return true;
}//Is it empty?
public boolean isempty(){
if(this.top==0){
return true;
}
return false;
}
//Stack out
public void pop(){
if(isempty()){
return ;
}
--this.top;
}
//Get the element at the top of the stack
public int gettop(){
if(isempty()){
return -1;
}
return this.elem[this.top-1];//Can't change the value of top, can't do -- Top
}
//Print all elements of the stack
public void show(){
for (int i=0;i<this.top;i++){
System.out.println(this.elem[i]);
}
}
}
public class test3 {
public static void main(String[] args) {
stack t1=new stack();
t1.rush(1);
t1.rush(3);
t1.rush(5);
t1.show();
System.out.println("The element at the top of the stack is"+t1.gettop());
}
}
Operation result:
1
3
5
Stack top element is 5