队列的顺序存储结构

队列是一种特殊的线性表,只允许在表的前端进行删除操作,只允许在表的后端进行插入操作。

队列的常用操作:

初始化:

返回队列的长度:

加入元素:

移除元素:

访问队列的前端元素:

判断队列是否为空:

清空队列:

package MyJava2;

import java.util.Arrays;

public class SequenceQueue {
    private int DEFAULT_SIZE=10;
    private int capacity;
    private String[] elements;
    //保存队列的元素个数
    private int front=0;
    private int rear=0;

    public SequenceQueue(){
        capacity=DEFAULT_SIZE;
        elements=new String[capacity];
    }
    public SequenceQueue(String data){
        capacity=DEFAULT_SIZE;
        elements=new String[capacity];
        elements[0]=data;
        rear++;
    }
    public SequenceQueue(String data,int inational){
        capacity=inational;
        elements=new String[capacity];
        elements[0]=data;
        rear++;
    }

    public int len(){
        return rear-front;
    }

    public void add(String data){//插入队列
        if(rear>capacity-1){
            throw new IndexOutOfBoundsException("OutOfIndex");
        }
        elements[rear++]=data;
    }
    public String remove(){//移除队列
        if(empty()){
            throw new IndexOutOfBoundsException("null");
        }
        String old=elements[front];
        elements[front++]=null;
        return old;
    }
    public String getFront(){//返回队列元素但不删除
        if(empty()){
            throw new IndexOutOfBoundsException("null");
        }
        return elements[front];
    }
    public boolean empty() {
        return rear==front;
    }
    public void clear(){
        Arrays.fill(elements,null);
        front=0;
        rear=0;
    }
    public String toString(){
        StringBuffer sb=new StringBuffer();
        for(int i=front;i<rear;i++){
            sb.append(elements[i].toString()+",");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        SequenceQueue queue=new SequenceQueue("1",3);
        queue.add("2");
        queue.add("3");
        System.out.println(queue.toString());
        System.out.println(queue.remove());
        System.out.println(queue.getFront());
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream答案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值