stack in java data structure

As a structure for storing data, the stack is based on the last in first out table (Last In First Out, referred to as LIFO, some people say that it is the same as the principle of first in, last out, don't be confused 233) Its limitation is that only one end of the table is allowed. Insertion and deletion operations, the end of the operation on the stack is called the top of the stack, and the other end is called the bottom of the stack. When we insert a new element into a stack, it is called a push or a push. At this time, the Push() method is called to delete from the stack. The element is called popped or popped, and the Pop() method is called. It's like a bullet clip, which is pressed into the bullet first and then ejected last. Examples of it like the bracket matching problem, the maze problem, etc. will be listed in a later article update. The following is the code of the stack (in actual use, it is an encapsulated class that can be called directly, but we also need to understand the idea of ​​mastering it).

package csnd;

public class Stackx {
	private int array[];
	private int top;
	private int maxSize;
	public Stackx() {
		
	}
	public Stackx(int max) {
		top=-1;
		maxSize = max;
		array = new int[maxSize];
	}
    public void push(int number) {//Push into the stack, push each element to the bottom of the stack
        array[++top] = number;
	}
    public int pop() {//Popping the stack, which can be understood as deleting, but not in the real sense of making it disappear, it is still there in memory, and it will only be overwritten when other elements come in
    	return array[top--];//top-- is here. If it is --top, it will be out of bounds when judging whether it is empty or not when popping the stack, because --top will decrease by one first
    			
	}
    public int peek() {//View the elements at the top of the stack
		return array[top];
	}
    public boolean isEmpty() {
		return (top == -1);
	}
    public boolean isFull() {
		
        return (top == maxSize-1);
	}
    public static void main(String[] args) {
		Stackx theStack = new Stackx(10);
		//When the user calls the push() method, he actually needs to call the isFull() method to determine whether the stack is full, which is omitted here
		theStack.push(10);
		theStack.push(25);
		theStack.push(78);
		theStack.push(15);
		while(!theStack.isEmpty())
		{
			int value = theStack.pop();//Pop the stack, pop elements from the top of the stack one by one
			System.out.print(value+" ");
		}
		System.out.println();
	}
}
//operation result

15 78 25 10 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325902866&siteId=291194637