zoukankan      html  css  js  c++  java
  • 数组实现栈和队列


    /**
    * 数组实现栈和队列
    */
    public class ArrayToQueueAndStack {

    public static class MyStack<T> {

    public Object[] arr;

    public int size;

    public int limit;

    public MyStack(int limit) {
    this.arr = new Object[limit];
    this.limit = limit;
    }

    public void push(T value) {
    if (size == limit) {
    System.out.println("the stack is full");
    return;
    }
    arr[size++] = value;
    }

    public T pop() {
    if (isEmpty()) {
    System.out.println("the stack is empty");
    return null;
    }
    return (T) arr[--size];
    }

    public boolean isEmpty() {
    return size == 0;
    }

    }

    public static class MyQueue<T> {

    public Object[] arr;

    public int pushIndex;

    public int pollIndex;

    public int size;

    public int limit;

    public MyQueue(int limit) {
    this.arr = new Object[limit];
    this.limit = limit;
    }

    public void push(T value) {
    if (size == limit) {
    System.out.println("the queue is full");
    return;
    }
    arr[pushIndex] = value;
    size++;
    pushIndex = nextIndex(pushIndex);
    }

    public T poll() {
    if (isEmpty()) {
    System.out.println("the queue is empty");
    return null;
    }
    T value = (T) arr[pollIndex];
    size--;
    pollIndex = nextIndex(pollIndex);
    return value;
    }

    public boolean isEmpty() {
    return size == 0;
    }

    private int nextIndex(int pushIndex) {
    return ++pushIndex % limit;
    }

    }

    }

    /* 如有错误,欢迎批评指正 */
  • 相关阅读:
    linux top详解
    软件人才必须具备的素质
    合格程序员每天每周每月每年应该做的事
    正则匹配任意字符(包括换行)
    软件测试方案
    LInux进程间的通信方式有哪儿些?
    三网融合
    php路径问题
    xp 安装SATA AHCI驱动
    进程与线程的区别
  • 原文地址:https://www.cnblogs.com/laydown/p/12798221.html
Copyright © 2011-2022 走看看