模拟实现 队列 - 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];
        }
    }
}

你可能感兴趣的:(数据结构,java,算法,数据结构,链表,推荐算法)