数据结构与算法之队列

倖福魔咒の 提交于 2019-12-17 03:45:08

队列是一种只允许在一端插入数据(队尾),在另一端删除数据(队头)的操作的特殊线性表。

队列的特点:先进先出

队列可以用数组实现,称为顺序队列,又叫循环队列。也可以用链表实现,称为链式队列。

链式队列:

package queue.com;

public class MyListQueue {
    class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }
    Node front;
    Node rear;
    int usedSize;

    //判断是否为空
    public boolean isEmpty() {
        return usedSize == 0;
    }

    // 入队(尾插)
    public void offer(int data) {
        Node node = new Node(data);
        if (isEmpty()) {
            this.front = node;
            this.rear = node;
        } else {
            this.rear.next = node;
            this.rear = node;
        }
        this.usedSize++;
    }

    //出队(从头出)
    public int poll() {
        int tmp = this.front.data;
        this.front = this.front.next;
        this.usedSize--;
        return tmp;
    }

    //弹出队头元素
    public int peek() {
        return this.front.data;
    }
 }

顺序队列(循环队列):

package queue.com;

public class MyCircularQueue {

        public int[] elem;
        public int front;
        public int rear;
        public int usedSize;
        public MyCircularQueue(int k) {
            this.elem = new int[k];
            this.front = 0;
            this.rear = 0;
            this.usedSize = 0;
        }
        //进队列
        public boolean enQueue(int value) {
          if (isFull()) {
              return false;
          }
          this.elem[rear] = value;
          this.rear = (this.rear + 1) % this.elem.length;
          this.usedSize++;
          return true;
        }
        //出队列
        public boolean deQueue() {
            if (isEmpty()) {
                return false;
            }
            this.front = (this.front+1) % this.elem.length;
            this.usedSize--;
            return true;
        }
        //弹出队头元素
        public int Front() {
            if(isEmpty()) {
                return -1;
            }
            return this.elem[this.front];
        }
        //弹出队尾元素
        public int Rear() {
            if(isEmpty()) {
                return -1;
            }
            int index = this.rear == 0 ? index = this.elem.length-1 : this.rear-1;
            return elem[index];
        }

        public boolean isEmpty() {
            return this.front == this.rear;
        }

        public boolean isFull() {
            return this.front == (this.rear+1)%this.elem.length;
        }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!