JAVAは、単一リンクリストを使用してスタックをシミュレートします

public class LinkedListStackDemo {

    public static void main(String[] args) {


        ShuJu shuJu1 = new ShuJu(1);
        ShuJu shuJu2 = new ShuJu(2);
        ShuJu shuJu3 = new ShuJu(3);
        ShuJu shuJu4 = new ShuJu(4);
        ShuJu shuJu5 = new ShuJu(5);
        ShuJu shuJu6 = new ShuJu(6);
        ShuJu shuJu7 = new ShuJu(7);

        Stack stack = new Stack();
        stack.push(shuJu1);
        stack.push(shuJu2);
        stack.push(shuJu3);
        stack.push(shuJu4);
        stack.push(shuJu5);
        stack.push(shuJu6);


       stack.pop();
        System.out.println("出栈后");
        stack.list();
        System.out.println("再加入");
        stack.push(shuJu7);
        stack.list();

    }
}

class Stack{
    private ShuJu top = new ShuJu(0);//作为栈底前一个元素节点

    //判断栈是否空
    public void isEmpty(){
        if (top.getNext() == null){
            System.out.println("栈空");
        }
    }

    //入栈
    public void push(ShuJu shuJu){
        ShuJu temp = top;
        while (true){  //遍历找到最后一个节点 添加数据
           if (temp.next==null){
               break;
           }
          temp=temp.next;
        }
        temp.next=shuJu;
    }

    //出栈
    public void pop(){
        if (top.next == null){
            System.out.println("栈空");
            return;
        }
        ShuJu temp = top;
        while (true){  //遍历找到倒数第二个元素节点
            if (temp.next.next == null){
                break;
            }
            temp=temp.next;
        }
        System.out.println(temp.next+"出栈");
        temp.next=null;  //出栈后把最后一个节点移除
    }

    //遍历栈
    public void list(){
        if (top.next ==null){
            System.out.println("栈空");
            return;
        }
        ShuJu temp = top;
        while (true){
            if (temp.next == null){
                break;
            }
            temp=temp.next;
            System.out.println(temp);
        }
    }

}
class ShuJu{
    public int shu;
    public ShuJu next;

    public ShuJu(int shu){
        this.shu=shu;
    }

    public int getShu() {
        return shu;
    }

    public void setShu(int shu) {
        this.shu = shu;
    }

    public ShuJu getNext() {
        return next;
    }

    public void setNext(ShuJu next) {
        this.next = next;
    }
    @Override
    public String toString() {
        return "ShuJu{" +
                "shu=" + shu +
                '}';
    }
}

 

おすすめ

転載: blog.csdn.net/qq_41556688/article/details/113384259