l4 使用栈(先进后出)来实现队列(先进先出)的功能
程序员文章站
2022-03-14 15:05:51
...
#include <iostream>
#include <stack>
#include <queue>
class CQueue {
public:
CQueue(void);
~CQueue();
void appendTail(int node);
int deleteHeader();
private:
std::stack<int> * stack1;
std::stack<int> * stack2;
};
CQueue::CQueue(void) {
stack2 = new std::stack<int>;
stack1 = new std::stack<int>;
}
CQueue::~CQueue() {
delete stack1;
delete stack2;
}
void CQueue::appendTail(int node) {
stack1->push(node);
}
int CQueue::deleteHeader() {
if (stack2->empty()) {
while (!stack1->empty()) {
int tmp = stack1->top();
stack2->push(tmp);
stack1->pop();
}
}
if (stack2->empty()) {
printf("queue is empty");
return -1;
} else {
int returnValue = stack2->top();
stack2->pop();
return returnValue;
}
}
int main () {
CQueue *queue = new CQueue();
for (int i = 0; i < 10; i++) {
queue->appendTail(i);
}
for (int i = 0; i < 10; i++) {
int result = queue->deleteHeader();
printf("%d",result);
}
}
上一篇: 队列的链表实现
下一篇: 自动驾驶这个“小孩子”有多大了?