数据结构(2)-队列

文章目录

      • 一、队列结构的分类
      • 二、用Java实现普通队列结构
        • 2.1、基于数组
        • 2.2、基于链表


队列结构的特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

一、队列结构的分类

  • 普通对列结构(quene)
  • 双端对列结构(de-que)
  • 优先级队列结构(pri-que)

二、用Java实现普通队列结构

2.1、基于数组

public class Quene {
    private int size;//队列长度
    private int front;//队头索引
    private int rear;//队尾索引
    private int[] theQuene;//用数组构造队列结构
    private int items;//当前队列的元素数

    public Quene(int size){
        this.size = size;
        theQuene = new int[size];
        front = 0;
        rear = -1;
        items = 0;
    }

    //入队
    public void  insert(int value){
         if(rear == size - 1){
             //已经满队,另队尾为-1,从队头插入
            rear = -1;
         }
         theQuene[++rear] = value;
         items++;
    }

    //出队
    public int remove(){
        int temp = theQuene[front++];
        if(front == size){
            front = 0;
        }
        items--;
        return  temp;
    }

    //查看队头
    public int peek(){
        return theQuene[front];
    }

    //是否为空队
    public boolean isEmpty(){
        return (items == 0);
    }

    //是否为满队
    public boolean isFull(){
        return (items == size);
    }

    //对列当前元素数
    public int sizeOf(){
        return items;
    }
}

2.2、基于链表


public class LinkedListQuene<T> {
    //队列大小
    private int queneLength = 0;
    //队头
    private Node first;
    //队尾
    private Node last;

    //链表节点
    private class Node {
        //指向下一节点
        Node next;
        //节点携带的数据
        T value;
        private Node(T value) {
            this.value = value;
        }
    }

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


 
    public int depth() {
        return queneLength;
    }
  
    public int enquene(T value) {
        Node node = new Node(value);
        //分两种情况,空队列和非空队列
        if (isEmpty()) {
            first = node;
            last = node;
            queneLength++;
            return 1;
        } else {
             Node oldNode = last;
            oldNode.next = node;
            last = node;
            queneLength++;
            return 1;
        }
    }

 
    public T dequene() {
        if (isEmpty()) {
            return null;
        } else {
            T value = first.value;
            first = first.next;
            queneLength--;
            return value;
        }
    }
 
    public T peek() {
        if (isEmpty()) {
            return null;
        } else {
            return first.value;
        }
    }
}

你可能感兴趣的:(-----【数据结构】)