实现顺序栈和链式栈

即用数组和链表实现栈

// 基于数组实现的顺序栈
public class ArrayStack {
    private String[] item;//用于存储数据的数组
    private int n;//栈的大小
    private int count;//栈中数据的多少

    public ArrayStack(int n) {
        item = new String[n];
        this.n = n;
        this.count = 0;
    }

    public boolean push(String m) {
        if (count == n)
            return false;

        item[count] = m;
        ++count;
        return true;
    }

    public String pop() {
        if (count == 0) return null;
        String m = item[count - 1];
        --count;
        return m;
    }
}
View Code
//基于链表实现栈
public class ListStack {
  private Node nodePr=null;


    public ListStack() {
        nodePr = null;
    }

    public void push(int tmp) {
        Node newNode = new Node(tmp);
        if (nodePr == null) {
            nodePr = newNode;
        }
        newNode.next=nodePr;
        nodePr=newNode;
    }

    public Integer pop() {
        if (nodePr == null) {
            System.out.println("there is no node in this stack");
            return null;
        }
        int m = nodePr.data;
        nodePr=nodePr.next;
        return m;
    }

}
View Code

 

posted @ 2018-10-11 18:10  ZECDLLG  阅读(258)  评论(0)    收藏  举报