java实现栈:链式结构

首先是结点:一个链表由一个个结点构成

package com.cqupt.stack;

public class Node {
    private int value;
    private Node nextNode;

    public Node() {

    }

    public Node(int value, Node nextNode) {
        this.value = value;
        this.nextNode = nextNode;
    }

    public int getValue() {
        return value;
    }

    public Node getNextNode() {
        return nextNode;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public void setNextNode(Node nextNode) {
        this.nextNode = nextNode;
    }
}

然后是链式结构的栈:

package com.cqupt.stack;

public class LinkedStack {
    private Node top;
    int len;

    public LinkedStack() {
        top = null;
        len = 0;
    }

    //入栈:
    public void push(int value) {
        Node newNode = new Node();
        newNode.setValue(value);
        newNode.setNextNode(top);
        top = newNode;
        len++;

    }

    //出栈
    public int pop() {
        Node tempNode = top;
        top = top.getNextNode();

        len--;
        return tempNode.getValue();
    }

}

测试类:

package com.cqupt.stack;

public class Main {
    public static void main(String[] args) {
        LinkedStack ls=new LinkedStack();
        ls.push(2);
        ls.push(4);
        ls.push(5);
        System.out.println(  ls.pop());
        System.out.println(  ls.pop());

     
    }
}

控制台打印:

猜你喜欢

转载自blog.csdn.net/Handsome2013/article/details/81544413