Realization of stack dynamic linked list

package stack; 

/** 
 * @author Eightn0 
 * @create 2021-03-15 15:00 
 * Realize stack with dynamic linked list 
 */ 

/*Declare node*/ 
class Node{ 
    int data; 
    Node next; 

    public Node(int data) { 
        this.data = data; 
        this.next = null; 
    } 
} 

/*Use a linked list to implement the stack and design methods for 
pushing, popping , and judging whether the stack is empty*/ class StackByLink{ 
    public Node front;//point to the bottom of the stack The pointer at the end 
    public Node rear;//Pointer to the top of the stack 

    /*Determine whether the stack is empty: isEmpty()*/ 
    public boolean isEmpty(){ 
        return front == null;//Judge whether the stack is empty by the bottom pointer Empty 
    } 

    /*Print stack content: output_of_stack*/ 
    public void output_of_stack(){ 
        Node current = front;//Start from the bottom pointer 
        while (current != null){//The condition for jumping out of the loop: the printing is finished 
            System.out.println("["+current.data+"]"); 
            current=current .next;//The pointer moves down, and the next one is printed 
        } 
        System.out.println();//For aesthetics 
    } 

    /*Into the stack-add data at the top: insert*/ 
    public void insert(int data){ 
        Node newNode = new Node(data);// 
        Load the data to be added into the node if (this.isEmpty()){//If the current stack is empty, then the top and bottom pointers are on the new node 
            front = newNode; 
            rear = newNode; 
        }else {//The current stack is not empty, then add the node from the top, make the original top point to the new node, and then move the top pointer to the new node 
            rear.next = newNode; 
            rear = newNode; 
        } 
    }

    /*Pull the stack-delete data at the top: pop*/ 
    public void pop(){
        Node newNode; 
        if (isEmpty()){//Empty stack does not need to delete data 
            System.out.println("Currently empty stack"); 
            return; 
        } 
        newNode = front;//There is only one data in the stack 
        if (newNode = = rear){ 
                front = null; 
                rear = null; 
                System.out.println("Currently empty stack");//If you delete it, it will be empty 
        }else {//More general situation 
            while (newNode.next != rear ){ 
                newNode = newNode.next; 
            } 
            newNode.next = rear.next; 
            rear = newNode; 
        } 
    } 
}

Guess you like

Origin blog.csdn.net/vivian233/article/details/114836280