数据结构与算法(Java) 18:栈和队列

题目 用数组结构实现大小固定的队列和栈

1. 栈

思路:设置一个指针指向当前位置,若入栈,则往指针指向的位置存入数据,指针指向下一个位置;若出栈,则输出当前位置的数据,并将指针前移一位。

package algorithm.section3;

public class ArrayToStack {
    Integer size;
    Integer[] array;

    public ArrayToStack(int initialSize){
        if (initialSize < 0)
            throw new IllegalArgumentException("The init size is less than 0!");
        array = new Integer[initialSize];
        size = 0;
    }

    public Integer peek(){
        if (size == 0) return null;
        return array[size - 1];
    }

    public void push(int obj){
        if (size == array.length)
            throw new IndexOutOfBoundsException("The stack is full!");
        array[size++] = obj;
    }

    public Integer pop(){
        if (size == 0)
            throw new IndexOutOfBoundsException("The stack is empty!");
        return array[--size];
    }
}

2. 队列

思路:设置两个指针start和end分别指向队头和队尾。数据从队尾加入,从队头排出。设一个变量size记录当前队列中的成员个数。

package algorithm.section3;

public class ArrayToQueue {
    Integer size;
    Integer[] array;
    Integer start = 0;
    Integer end = 0;

    public ArrayToQueue(int initialSize){
        if (initialSize < 0)
            throw new IllegalArgumentException("The init size is less than 0!");
        array = new Integer[initialSize];
        size = 0;
    }

    public Integer peek(){
        if (size == 0) return null;
        return array[start];
    }

    public void push(Integer obj){
        if (size == array.length)
            throw new IndexOutOfBoundsException("The queue is full!");
        array[end] = obj;
        end = end == array.length - 1 ? 0 : end + 1;
        size++;
    }

    public Integer poll(){
        if (size == 0)
            throw new IndexOutOfBoundsException("The queue is empty!");
        int flag = start;
        start = start == array.length - 1 ? 0 : start + 1;
        size--;
        return array[flag];
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105589000