模拟实现 队列 - JAVA(使用链表,数组)

以链表实现

以数组实现


 

以链表实现


class Node{
    public int val;
    public Node next;
    public  Node(int val){
        this.val=val;
    }
}


public class MyQueue {
    public Node front;
    public Node rear;

    //入队-》尾插法
    public void offer(int val){
        Node node=new Node(val);
        if(front==null){
            front=node;
            rear=node;
        }
        else{
            rear.next=node;
            rear=node;
        }
    }

    //返回队头元素
    public int peek(){
        if(isEmpty()) {
            throw new RuntimeException("队列为空!");
        }
        return front.val;
    }

    //出队
    public int poll() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空!");
        }
        int tmp=front.val;
        front=front.next;
        return tmp;
    }

    //是否为空
    public boolean isEmpty(){
        return front==null;
    }

    public static void main(String[] args) {
        System.out.println();
    }
    
}

以数组实现

public class MyCircularQueue {
    public int[] elem;
    public int front;
    public  int rear;

    public MyCircularQueue(int k){
        this.elem=new int[k];
    }

    //是否为空
    public boolean isEmpty(){
        return this.front==rear;
    }

    //是否为满
    public boolean isFull() {
        if((rear+1)%elem.length==front){
            return true;
        }
        return false;
    }
    //入队操作
    public boolean enQueue(int value){
        if(isFull()){
            return false;
        }
        elem[rear]=value;
        rear=(rear+1)%elem.length;
        return true;
    }

    //出队操作
    public boolean deQueue(){
        if(isEmpty()) {
            return false;
        }
        front=(front+1)% elem.length;
        return true;
    }

    //获取队头元素
    public int Front(){
        if(isEmpty()) {
            return -1;
        }
        return elem[front];
    }

    //获取队尾元素
    public int Rear(){
        if(isEmpty()) {
            return -1;
        }
        if(rear==0){
            return elem[elem.length-1];
        }
        else{
            return elem[rear-1];
        }
    }
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值