• 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());
        }
    }
  • 相关阅读:
    PHP读取MySQL中文乱码
    dotnet如何使用资源文件
    常见的隐藏地址的流媒体下载方法(转)
    圣诞礼物:Google Maps API开发样例一则
    Google EarthMapsKML核心开发技术揭秘 一个完整的Google Maps应用
    WEB界面测试用例~ 收藏
    通过xmlhttp实现报告归档
    转换长日期为短日期
    做delphi控件的笔记
    Reflector使用手记
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513141.html
Copyright © 2020-2023  润新知