【队列 & 栈】(一) 队列:先入先出的数据结构

目录

一、先入先出的数据结构 

二、队列 - 实现

三、循环队列

四、设计循环队列

4.1 题目要求

4.2 解决过程

五、循环队列 - 实现

六、队列 - 用法

七、数据流中的移动平均值 (PLUS 会员专享)


一、先入先出的数据结构 

 

文章链接:https://leetcode-cn.com/explore/learn/card/queue-stack/216/queue-first-in-first-out-data-structure/862/ 


二、队列 - 实现

// C++ implementation
#include <iostream>

class MyQueue {
    private:
        // store elements
        vector<int> data;       
        // a pointer to indicate the start position
        int p_start;            
    public:
        MyQueue() {p_start = 0;}
        /** Insert an element into the queue. Return true if the operation is successful. */
        bool enQueue(int x) {
            data.push_back(x);
            return true;
        }
        /** Delete an element from the queue. Return true if the operation is successful. */
        bool deQueue() {
            if (isEmpty()) {
                return false;
            }
            p_start++;
            return true;
        };
        /** Get the front item from the queue. */
        int Front() {
            return data[p_start];
        };
        /** Checks whether the queue is empty or not. */
        bool isEmpty()  {
            return p_start >= data.size();
        }
};

int main() {
    MyQueue q;
    q.enQueue(5);
    q.enQueue(3);
    if (!q.isEmpty()) {
        cout << q.Front() << endl;
    }
    q.deQueue();
    if (!q.isEmpty()) {
        cout << q.Front() << endl;
    }
    q.deQueue();
    if (!q.isEmpty()) {
        cout << q.Front() << endl;
    }
}

 

文章链接:https://leetcode-cn.com/explore/learn/card/queue-stack/216/queue-first-in-first-out-data-structure/863/ 


三、循环队列


四、设计循环队列

4.1 题目要求

 

4.2 解决过程

法一:在构造函数中初始化三个属性成员:self._data 表示元素全初始化为 None 的 k 长度循环队列主体,使用列表推导式 [None for _ in range(k)] 会比使用 [None] * k 更高效且安全些;self._size 表示循环队列当前有效长度,初始长度为 0;self._front 表示循环队列当前队首的索引,从 0 开始。

除了题目要求实现的各方法,再附带一个 __len__() 方法用于 len() 函数查看循环队列长度。此外,还可在构造函数中增加属性成员 self.capacity = k 来取代 len(self._data) 获取循环队列容限 k,两种操作的复杂度均为 O(1)。

2020/06/22 - 96.67% - 最佳

# Python implementation
class MyCircularQueue:
    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        """
        self._data = [None for _ in range(k)]  # 初始化固定长度为k的队列
        self._size = 0  # 当前队列元素数
        self._front = 0  # 队首 index   
    
    def __len__(self) -> int:
        """
        Return the number of elements in the queue.
        """
        return self._size
    
    def isEmpty(self) -> bool:
        """
        Checks whether the circular queue is empty or not.
        """
        return self._size == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular queue is full or not.
        """
        return self._size == len(self._data)

    def enQueue(self, value: int) -> bool:
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        """
        if not self.isFull():
            end = (self._front + self._size) % len(self._data)  # 队尾后一位 index
            self._data[end] = value  # 入队
            self._size += 1  # 当前队列元素数 + 1
            return True  # 成功插入则返回 True
        else:
            return False
        
    def deQueue(self) -> bool:
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        """
        if not self.isEmpty():
            self._data[self._front] = None  # 队首元素删除
            self._front = (self._front + 1) % len(self._data)  # 队首 index 后移一位
            self._size -= 1  # 当前队列元素数 - 1
            return True  # 成功删除则返回 False
        else:
            return False
        
    def Front(self) -> int:
        """
        Get the front item from the queue.
        """
        if not self.isEmpty():
            return self._data[self._front]  # 返回队首元素
        else:
            return -1  # 队列为空返回 -1
        
    def Rear(self) -> int:
        """
        Get the last item from the queue.
        """
        if not self.isEmpty():
            rear = (self._front + self._size - 1) % len(self._data)  # 队尾 index, 注意区别于 end
            return self._data[rear]  # 返回队尾元素
        else:
            return -1  # 队列为空返回 -1
        
# ----------------------------------------------------------------------------------------------------
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()

五、循环队列 - 实现

// C++ implementation
class MyCircularQueue {
private:
    vector<int> data;
    int head;
    int tail;
    int size;
public:
    /** Initialize your data structure here. Set the size of the queue to be k. */
    MyCircularQueue(int k) {
        data.resize(k);
        head = -1;
        tail = -1;
        size = k;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    bool enQueue(int value) {
        if (isFull()) {
            return false;
        }
        if (isEmpty()) {
            head = 0;
        }
        tail = (tail + 1) % size;
        data[tail] = value;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    bool deQueue() {
        if (isEmpty()) {
            return false;
        }
        if (head == tail) {
            head = -1;
            tail = -1;
            return true;
        }
        head = (head + 1) % size;
        return true;
    }
    
    /** Get the front item from the queue. */
    int Front() {
        if (isEmpty()) {
            return -1;
        }
        return data[head];
    }
    
    /** Get the last item from the queue. */
    int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return data[tail];
    }
    
    /** Checks whether the circular queue is empty or not. */
    bool isEmpty() {
        return head == -1;
    }
    
    /** Checks whether the circular queue is full or not. */
    bool isFull() {
        return ((tail + 1) % size) == head;
    }
};

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * bool param_1 = obj.enQueue(value);
 * bool param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * bool param_5 = obj.isEmpty();
 * bool param_6 = obj.isFull();
 */

文章链接:https://leetcode-cn.com/explore/learn/card/queue-stack/216/queue-first-in-first-out-data-structure/866/


六、队列 - 用法

// C+ implementation
#include <iostream>

int main() {
    // 1. Initialize a queue.
    queue<int> q;
    // 2. Push new element.
    q.push(5);
    q.push(13);
    q.push(8);
    q.push(6);
    // 3. Check if queue is empty.
    if (q.empty()) {
        cout << "Queue is empty!" << endl;
        return 0;
    }
    // 4. Pop an element.
    q.pop();
    // 5. Get the first element.
    cout << "The first element is: " << q.front() << endl;
    // 6. Get the last element.
    cout << "The last element is: " << q.back() << endl;
    // 7. Get the size of the queue.
    cout << "The size is: " << q.size() << endl;
}

以上是 C++ 实现队列,关于 Python 可参照 pythonds 模块中的基本实现,以下是 pythonds.basic.queue 源码:

# Python implementation

>>> import pythonds.basic.queue as Queue
>>> help(Queue)  # 导入模块并查看基本接口
Help on module pythonds.basic.queue in pythonds.basic:

NAME
    pythonds.basic.queue

DESCRIPTION
    # Bradley N. Miller, David L. Ranum
    # Introduction to Data Structures and Algorithms in Python
    # Copyright 2005
    # 
    #queue.py

CLASSES
    builtins.object
        Queue
    
    class Queue(builtins.object)
     |  Methods defined here:
     |  
     |  __init__(self)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  dequeue(self)
     |  
     |  enqueue(self, item)
     |  
     |  isEmpty(self)
     |  
     |  size(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)

FILE
    e:\python36\lib\site-packages\pythonds\basic\queue.py

>>> pythonds.basic.queue.__file__  # 找到文件位置查看源码
'E:\\Python36\\lib\\site-packages\\pythonds\\basic\\queue.py'
# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005
# 
#queue.py

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

七、数据流中的移动平均值 (PLUS 会员专享)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值