数据结构-队列

目录

队列的使用

队列的模拟实现(链式结构)

循环队列

双端队列(Deque)


队列的使用

队列的模拟实现(链式结构)

public class MyQueue {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode last;

    public void offer(int val) {
        ListNode node = new ListNode(val);
        if (head == null) {
            head = last = node;
            node.prev = last;
            last = last.next;
        }
    }

    public int poll() {
        if (head == null) {
            return -1;
        }
        int ret = head.val;
        if (head.next == null) {
            head = null;
            last = null;
        } else {
            head = head.next;
            head.prev = null;
        }
        return ret;
    }

    public int peek() {
        if (head == null) {
            return -1;
        }
        return head.val;
    }

    public boolean isEmpty() {
        return head == null;
    }
}

循环队列

设计循环队列


class MyCircularQueue {

    public int[] elem;
    public int first;
    public int last;

    public MyCircularQueue(int k) {
        elem = new int[k + 1];
    }

    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        elem[last] = value;
        last = (last + 1) % elem.length;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        first = (first + 1) % elem.length;
        return true;
    }

    // 得到对头元素
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return elem[first];
    }

    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        int index = (last == 0) ? elem.length - 1 : last - 1;
        return elem[index];
    }

    public boolean isEmpty() {
        return first == last;
    }

    public boolean isFull() {
        return (last + 1) % elem.length == first;
    }
}

双端队列(Deque)

双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。那就说明元素可以从队头出队和入队,也可以从队尾出队和入队。

Deque是一个接口,使用时必须创建LinkedList的对象。

在实际工程中,使用Deque接口是比较多的,栈和队列均可以使用该接口。

Deque<Integer> stack = new ArrayDeque<>();//双端队列的线性实现

Deque<Integer> queue = new LinkedList<>();//双端队列的链式实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值