【数据结构与算法】-- 5. 如何实现一个队列(顺序队列和链式队列)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/YYZZHC999/article/details/89644239

队列跟栈一样, 也是一种操作受限的线性表数据结构。
它具有先进先出的特性, 支持在队尾插入元素, 在队头删除元素, 那究竟该如何实现一个队列呢?
跟栈一样, 队列可以用数组来实现, 也可以用链表来实现。 用数组实现的栈叫作顺序栈, 用链表实
现的栈叫作链式栈。 同样, 用数组实现的队列叫作顺序队列, 用链表实现的队列叫作链式队列。

顺序队列

package com.anomalous.array;

/**
 * 基于数组实现的队列
 *
 * @author 天赋吉运-杨晓慧
 * @create 2019-04-27 15:27
 */
public class ArrayQueue {

    //定义数组,数组大小,两个指针(头和尾)
    private String items[];     // 队列
    private int n;          // 队列内元素数量
    private int head;       // 队列内头指针位置
    private int tail;       // 队列内尾指针位置

    /**
     * 构造一个基于数组实现的队列
     * @param n 容量
     */
    public ArrayQueue(int n){
        //定义长度为n的数组
        this.items=new String[n];

        this.n=n;
        // 数组中头指针和尾指针
        this.head=0;
        this.tail=0;
    }

    /**
     * 入队操作
     * @param item 入队元素
     * @return 是否入队成功
     */
    public boolean inqueue(String item){

        // 判断队列是否满了,如果队列已满不能再进行入队操作
        if (this.tail==n) {
           if (head==0) {
               // tail=n && head=0表示整个队列都已经满了,前后都没有空位置了
               return false;
            }
            // 只有tail=0表示队尾已经满了,但队首还有空位置
            // 需要数据搬移,将后面的数据往前移动,为队列腾出位置,然后新入队的数据才能放入队尾
            for (int i = head; i < tail; i++) {
                //从队首开始,依次往前移动head位
                 this.items[i-head]= this.items[i];
            }

            // 数据搬移完之后需要更新head和tail指针的位置
            // head指向0位,tail往前移动head个位置;
            head=0;
            tail-=head;
        }

        // 放在队列的最后一位
        this.items[tail]=item;
        // 头指针不变,尾指针的位置后移一位
        ++tail;
        return true;
    }

    /**
     * 出队操作
     * @return 出队元素
     */
    public String outqueue(){
        //判断对内是否有元素
        if (this.head==this.tail) {
            // 队首指针与队尾指针在同一位置表示队列为空
            return null;
        }
        // 取出队首元素放入临时变量
        String temp=items[head];

        // 从head指针部分出队,head后移一位
        ++head;
        return temp;
    }
}


链式栈

猜你喜欢

转载自blog.csdn.net/YYZZHC999/article/details/89644239