zoukankan      html  css  js  c++  java
  • Java栈的两种实现

    1. 基于数组

    package Algorithm.learn;
    
    import java.util.Arrays;
    
    /**
     * Created by liujinhong on 2017/3/7.
     */
    public class MyStack<E> {
        private Object[] stack;
        private int size;
        MyStack() {
            stack = new Object[10];
            size = 0;
        }
    
        public boolean isEmpty() {
            return size == 0;
        }
    
        public E peek() {
            if (isEmpty()) {
                return null;
            }
            return (E)stack[size-1];
        }
    
        public E pop() {
            if (isEmpty()) {
                return null;
            }
            size--;
            return (E)stack[size];
        }
    
        private void ensureCapacity(int size) {
            if (size > stack.length) {
                int len = stack.length + 10;
                stack = Arrays.copyOf(stack, len);
            }
        }
    
        public E push(E e) {
            ensureCapacity(size+1);
            stack[size++] = e;
            return e;
        }
    
        public static void main(String[] args) {
            MyStack<String> stack = new MyStack<>();
            stack.push("a");
            stack.push("b");
    
            System.out.println(stack.peek());
            System.out.println(stack.pop());
            System.out.println(stack.pop());
            System.out.println(stack.pop());
        }
    }

    2. 基于链表

    package Algorithm.learn;
    
    /**
     * Created by liujinhong on 2017/3/7.
     */
    
    class Node<E> {
        Node<E> next = null;
        E data;
        public Node(E data) {
            this.data = data;
        }
    }
    
    public class ListStack<E> {
        Node<E> top = null;
    
        boolean isEmpty() {
            return top == null;
        }
    
        public void push(E item) {
            Node<E> node = new Node<E>(item);
            node.next = top;
            top = node;
        }
    
        public E pop() {
            if (this.isEmpty()) return null;
            E data = top.data;
            top = top.next;
            return data;
        }
    
        public E peek() {
            if (this.isEmpty()) return null;
            return top.data;
        }
    
        public static void main(String[] args) {
            ListStack<Integer> stack = new ListStack<>();
            stack.push(1);
            stack.push(2);
    
            System.out.println(stack.pop());
            System.out.println(stack.pop());
        }
    }
  • 相关阅读:
    警示
    【拒绝挂分】盘点蒟蒻ghy的各种sb错误
    牛客NOIPtg day5 B-demo的gcd
    数字校园APP——视频分享
    数字校园APP——软件需求规格说明书
    数字校园APP——可行性报告分析
    数字校园APP开发与应用
    结对编程第二次作业——四则运算自动生成器
    软件工程第四次作业
    软件工程第三次作业
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513141.html
Copyright © 2011-2022 走看看