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());
        }
    }
  • 相关阅读:
    模板方法设计模式(未完待续)
    适配器模式
    g2o:一种图优化的C++框架
    U14.04 teamviewer install
    小教训
    卡2-SLAM
    Odometry的发布和发布odom到base_link的tf变换
    #pragma once
    友元
    Ubuntu 14.04 安装配置强大的星际译王(stardict)词典
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513141.html
Copyright © 2011-2022 走看看