利用数组和链表实现一个队列

什么是队列

可以把它想象成排队买票,先来的先买,后来的人只能站末尾,不允许插队。

队列的最大特点就是“先进先出”。

栈有两个基本操作:入栈 push()和出栈 pop()。入栈和出栈都是在栈顶。

队列最基本的操作也是两个:入队 enqueue(),放一个数据到队列尾部;出队 dequeue(),从队列头部取一个元素。

队列跟栈一样,也是一种操作受限的线性表数据结构。

 

顺序队列和链式队列

队列可以用数组来实现,也可以用链表来实现。

用数组实现的队列,我们叫作顺序队列。

用链表实现的队列,我们叫作链式队列。

数组实现一个顺序队列

用数组实现之前先说一个概念:假溢出

假溢出

作为队列用的存储区还没有满,但队列却发生了溢出,我们把这种现象称为"假溢出"

解决假溢出有两种方案:

一、将队列元素向前搬移。(如下代码就是利用此解决方案)

二、将队列看成首尾相连,即循环队列。

public class ArrayQueue {
    private String[] items;
    private int head;        //队头
    private int tail;        //队尾
    private int size;

    public ArrayQueue(int n) {
        this.items = new String[n];
        this.size = n;
        this.head = 0;
        this.tail = 0;
    }

    public boolean enQueue(String item) {
        if (tail == size) {
            if (head == 0) {          //真正的空间已满
                System.out.println("队列已满,入队失败");
                return false;
            }
            //假溢出,队尾没有空间了,进行数据搬移
            for(int i = head;i<tail;i++){
                items[i-head] = items[i];
            }
                tail = tail - head;       //重置head和tail
                head = 0;
        }
        items[tail] = item;
        ++tail; 
        return true;
    }

    public String deQueue() {
        if (head == tail) {
            System.out.println("队列为空");
            return null;
        }
        String tmp = items[head];
        ++head;
        return tmp;
    }
}

用链表实现一个链式队列

public class LinkedListQueue {
    private static class Node {
        private String data;
        private Node next;

        public Node(String data, Node next) {
            this.data = data;
            this.next = next;
        }

        public String getData() {
            return data;
        }
    }
    private Node head = null;
    private Node tail = null;

    public void enQueue(String value) {
        Node newNode = new Node(value,null);
        if (head==tail){
            head = tail =newNode;
        }
        tail.next = newNode;
        tail = newNode;
    }

    public String deQueue() {
        if(head==null){
            System.out.println("队列为空");
            return null;
        }
        String value = head.data;
        head = head.next;     //若队列中只有一个数据,head.next为null,此时tail仍指向出队列的节点,需要把tail置空
        if (head==null){
            tail = null;
        }
        return value;
    }
}
发布了91 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42006733/article/details/104327844