用数组或链表实现栈

    直接上代码,push时直接往数组末尾存,pop时直接在数组末尾取 

/**
 * @create 2017-09-22 21:23
 */
public class StackDemo {
    public static int N = 0;
    public static int[] a = new int[1];

    public void resize(int n) { //动态调整数组大小
        int t[] = new int[n];
        for (int i = 0; i < N; i++) {
            t[i] = a[i];
        }
        a = t;
    }

    public void push(int i) {
        a[N++] = i;
        if (isFull()) {
            resize(size() * 2);
        }
    }

    public int peek() { //查看栈顶元素
        if (N == 0) {
            throw new RuntimeException("Stack is empty.");
        }
        return a[N - 1];
    }

    public boolean isFull() {
        return N >= size() - 1;
    }

    public boolean isEmpty() {
        return N == 0;
    }
    public int pop() {
        if (N == 0) {
            throw new RuntimeException("Stack is empty.");
        }
        int t = a[--N];
        if (N <= size() / 2) {
            resize(size() / 2);
        }
        return t;
    }

    public int size() {
        return a.length;
    }

    public static void main(String[] args) {
        StackDemo s = new StackDemo();
        for (int i = 0; i < 10; i++) {
            s.push(i);
        }

        while (!s.isEmpty()) {
            System.out.println(s.pop());
        }
    }
}

    当然,也可以用单链表来实现栈,直接在链表头部删除或插入元素即可

/**
 * @create 2017-09-22 21:23
 */
public class StackDemo {
    public static int len = 0;
    Node head = null;
    private class Node {
        int num;
        Node next;

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

    public void push(int n) {
        if (isEmpty()) {
            head = new Node(n);
        } else {  //在链表头部插入新的结点
            Node old = head;
            head = new Node(n);
            head.next = old;
        }
        len++;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty.");
        }
        int t = head.num;
        head = head.next;
        len--;
        return t;
    }

    public int peek() { //查看栈顶元素
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty.");
        }
        return head.num;
    }

    public int size() {
        return len;
    }

    public boolean isEmpty() {
        return head == null; //也可以是len == 0
    }

    public static void main(String[] args) {
        StackDemo s = new StackDemo();
        for (int i = 0; i < 10; i++) {
            s.push(i);
        }
        System.out.println("size: " + s.size());
        while(!s.isEmpty()) {
            System.out.println(s.pop());
        }
    }
}

 

转载于:https://my.oschina.net/yitiaoxianyu/blog/1542113

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值