如何实现一个双端队列?
The following article is from 小K算法 Author 小K算法
01故事起源
还需要定义2个指针,头指针和尾指针。
02插入和删除
但数组是定长的,如果多次插入删除,tail指针就会超出数组范围,而前面其实还是有空间的,所以常用的还是循环队列。
03循环队列
通过取模就可以实现循环。
当head==tail时,即为队空。
当head==(tail+1)%n时,即为队满。如果队列长度为n,则只能装n-1个元素,最后一个元素要空着。因为如果放入元素,tail会和head重合,就无法判断是队空还是队满。
04双端队列
05代码实现
class Deque {
public:
explicit Deque(int capacity);
void PushFront(const T &node);
void PushBack(const T &node);
T PopFront();
T PopBack();
T Front() { return data_[head_]; }
T Back() { return data_[(tail_ - 1 + capacity_) % capacity_]; }
bool IsNotEmpty() { return head_ != tail_; };
bool IsEmpty() { return head_ == tail_; }
bool IsFull() { return (tail_ + 1) % capacity_ == head_; };
int Size();
int Head() { return head_; }
int Tail() { return tail_; }
public:
int capacity_, head_, tail_;
T *data_;
};
Deque<T>::Deque(int capacity) {
capacity_ = capacity;
head_ = tail_ = 0;
data_ = new T[capacity_];
}
void Deque<T>::PushBack(const T &node) {
if (IsFull()) {
std::__throw_logic_error("queue is full");
}
data_[tail_] = node;
tail_ = (tail_ + 1) % capacity_;
}
template<typename T>
void Deque<T>::PushFront(const T &node) {
if (IsFull()) {
std::__throw_logic_error("queue is full");
}
head_ = (head_ - 1 + capacity_) % capacity_;
data_[head_] = node;
}
T Deque<T>::PopBack() {
if (IsEmpty()) {
std::__throw_logic_error("queue is empty");
}
tail_ = (tail_ - 1 + capacity_) % capacity_;
return data_[tail_];
}
template<typename T>
T Deque<T>::PopFront() {
if (IsEmpty()) {
std::__throw_logic_error("queue is empty");
}
head_ = (head_ + 1) % capacity_;
return data_[(head_ - 1 + capacity_) % capacity_];
}
int Deque<T>::Size() {
if (head_ <= tail_) {
return tail_ - head_;
} else {
return tail_ + (capacity_ - head_);
}
}
Deque<int> deq(10);
deq.PushBack(2);
deq.PushFront(1);
deq.PushFront(0);
deq.PushBack(3);
printf("head=%d tail=%d size=%d back=%d\n", deq.Head(), deq.Tail(), deq.Size(), deq.Back());
while (deq.Size() > 2) {
printf("%d\n", deq.PopBack());
}
deq.PushBack(2);
deq.PushFront(1);
deq.PushFront(0);
deq.PushBack(3);
printf("head=%d tail=%d size=%d front=%d\n", deq.Head(), deq.Tail(), deq.Size(), deq.Front());
while (deq.IsNotEmpty()) {
printf("%d\n", deq.PopFront());
}
return 0;
}
06总结
【☝🏼点击查看更多详情】
推荐阅读: