双端队列实现 :栈、链表、数组多解法

题目

LeetCode 641题:实现双端队列
设计实现双端队列。
你的实现需要支持以下操作:
MyCircularDeque(k):构造函数,双端队列的大小为k。
insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
isEmpty():检查双端队列是否为空。
isFull():检查双端队列是否满了。

写在前面

每当看到类似的题目,脑海中的第一想法就会是用栈或者队列来实现。

解法一:双栈

使用栈来实现双端队列需要使用两个栈,因为一个栈无法实现两端插入和删除,并且需要将两端固定。如栈1用来充当队列头,栈2用来充当队列尾
这样,使用栈来实现需要注意以下几点:

  • 在取元素时,如果该栈为空,但是另外的栈可能不为空,所以需要将另外一个栈中的数据拷贝过来;
    例如,当从头部栈中取元素时,如果头部栈为空但是尾部栈不为空,则需要从尾部栈中读取。从尾部栈取元素亦然。
  • 在删除元素时,如果该栈为空,但是另外的栈可能不为空,所以需要从另外一个栈中进行删除;

所以必然会造成的问题是,在读取或删除过程中,会产生多次的栈复制。
下图以一个具体的例子展示了双端队列的整个过程以及极端情况:
image.png

class MyCircularDeque {
public:
    int capacity;
    stack<int> sta_in;
    stack<int> sta_out;
    int size;
    /** Initialize your data structure here. Set the size of the deque to be k. */
    MyCircularDeque(int k) {
        capacity = k;
        size = 0;
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value) {
        if (isFull()) return false;
        sta_out.push(value);
        size++;
        return true;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value) {
        if (isFull()) return false;
        sta_in.push(value);
        size++;
        return true;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront() {
        if (isEmpty()) return false;
        if (sta_out.empty()) in2out();
        sta_out.pop();
        size--;
        return true;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast() {
        if (isEmpty()) return false;
        if (sta_in.empty()) out2in();
        sta_in.pop();
        size--;
        return true;
    }

    /** Get the front item from the deque. */
    int getFront() {
        if (isEmpty()) return -1;
        if (sta_out.empty()) in2out();
        return sta_out.top();
    }

    /** Get the last item from the deque. */
    int getRear() {
        if (isEmpty()) return -1;
        if (sta_in.empty()) out2in();
        return sta_in.top();
    }

    /** Checks whether the circular deque is empty or not. */
    bool isEmpty() {
        return size == 0;
    }

    /** Checks whether the circular deque is full or not. */
    bool isFull() {
        return size == capacity;
    }
    void in2out() {
        while (!sta_in.empty()) {
            sta_out.push(sta_in.top());
            sta_in.pop();
        }
        return;
    }
    void out2in() {
        while (!sta_out.empty()) {
            sta_in.push(sta_out.top());
            sta_out.pop();
        }
        return;
    }
};

解法二:双向链表

解法一的栈复制会造成没必要的耗时,甚至会出现极端情况。那么能否消除内存之间的复制,当然可以,使用链表,链表是一种不连续内存存储结构,任何操作都不需要大量的内存复制操作。
       另外,如果使用单链表的话,当要删除尾部数据时,由于无法找到尾部节点的前驱,所以会产生O(n)的查询时间复杂度。所以,最好使用双向链表实现。
       使用链表实现双端队列唯一需要注意的就是头指针head和尾指针tail的更新。

struct _ListNode {
    int val;
    _ListNode* pre;
    _ListNode* next;
    _ListNode(int value) :val(value) {
        pre = NULL;
        next = NULL;
    }
};
class MyCircularDeque {
public:
    int capacity;
    _ListNode* head;
    _ListNode* tail;
    int size;
    /** Initialize your data structure here. Set the size of the deque to be k. */
    MyCircularDeque(int k) {
        capacity = k;
        size = 0;
        head = NULL;
        tail = NULL;
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value) {
        if (isFull()) return false;
        _ListNode* newNode = new _ListNode(value);
        newNode->next = head;
        if (head != NULL) head->pre = newNode;
        head = newNode;
        if (++size == 1) tail = newNode;
        return true;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value) {
        if (isFull()) return false;
        _ListNode* newNode = new _ListNode(value);
        newNode->pre = tail;
        if (tail != NULL) tail->next = newNode;
        tail = newNode;
        if (++size == 1) head = newNode;
        return true;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront() {
        if (isEmpty()) return false;
        _ListNode* node2Delete = head;
        head = head->next;
        if (head != NULL) head->pre = NULL;
        delete node2Delete;
        if (--size == 0) tail = NULL;
        return true;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast() {
        if (size == 0) return false;
        _ListNode* node2Delete = tail;
        tail = tail->pre;
        if (tail != NULL) tail->next = NULL;
        delete node2Delete;
        if (--size == 0) head = NULL;
        return true;
    }

    /** Get the front item from the deque. */
    int getFront() {
        return isEmpty() ? -1 : head->val;
    }

    /** Get the last item from the deque. */
    int getRear() {
        return isEmpty() ? -1 : tail->val;
    }

    /** Checks whether the circular deque is empty or not. */
    bool isEmpty() {
        return size == 0;
    }

    /** Checks whether the circular deque is full or not. */
    bool isFull() {
        return size == capacity;
    }
};

解法三:数组

       使用链表可以实现,那么,当然也可以使用数组实现。其实最开始也想到了数组,但是还是以定势的思维想着:在头部插入时,需要移动整个数组,造成了O(n)的时间复杂度。没想到的是可以使用移动指针来“移动”固定的数组,即只需要移动head和tail两个指针(非C++指针)来控制队列在数组上的相对位置即可。
       使用数组需要注意以下几点:

  • head:始终指向队列首元素
  • tail:始终指向队列尾元素的下一个,如果越界则循环
  • 需要对判断数组空和数组满的条件做区分(正常情况下都是 head == tail)
    可以使用较普遍的做法:将数组大小设定为队列大小+1(即数组大小 = 队列容量+1;),这样可以始终维持一个空位置,当队列满的时候,尾指针tail指向该空位置。
    那么,判断队列空:head == tail;判断队列满: (tail+1)%capacity == head;
  • 指针+1或者-1可能会越界
    使用+capacity和取模操作来保证索引不越界

下图以一个具体的例子展示了双端队列的整个过程:
image.png

class MyCircularDeque {
public:
    vector<int> data;
    int capacity;
    int head;//指向队列的首元素
    int tail;//指向队列最后一个元素的下一位
    /** Initialize your data structure here. Set the size of the deque to be k. */
    MyCircularDeque(int k) {
        capacity = k + 1;
        //需初始化k+1个值
        while (k-- > -1) data.emplace_back(0);
        head = 0;
        tail = 0;
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value) {
        if (isFull()) return false;
        head = (head - 1 + capacity) % capacity;
        data[head] = value;
        return true;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value) {
        if (isFull()) return false;
        data[tail] = value;
        tail = (tail + 1) % capacity;
        return true;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront() {
        if (isEmpty()) return false;
        head = (head + 1) % capacity;
        return true;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast() {
        if (isEmpty()) return false;
        tail = (tail - 1 + capacity) % capacity;
        return true;
    }

    /** Get the front item from the deque. */
    int getFront() {
        return isEmpty() ? -1 : data[head];
    }

    /** Get the last item from the deque. */
    int getRear() {
        return isEmpty() ? -1 : data[(tail - 1 + capacity) % capacity];
    }

    /** Checks whether the circular deque is empty or not. */
    bool isEmpty() {
        return head == tail;
    }

    /** Checks whether the circular deque is full or not. */
    bool isFull() {
        return (tail + 1) % capacity == head;
    }
};

总结

栈:思路清晰,代码简洁。比较耗时,极端情况需要来回复制栈,当然应该也是可以做优化的。
链表:思路清晰,代码较长,无内存复制,需要时刻注意头指针head和尾指针tail的更新。
数组:思路稍复杂,代码简洁,需要始终维持一个空变量空间。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值