概述
c++利用栈实现队列和利用队列实现栈
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class Queue {
public:
void pop() {
if (data1.empty()) {
cout << "queue is null" << endl;
return;
}
while (!data1.empty()) {
data2.push(data1.top());
data1.pop();
}
data2.pop();
while (!data2.empty()) {
data1.push(data2.top());
data2.pop();
}
}
void push(int temp) {
data1.push(temp);
}
int front() {
if (data1.empty()) {
cout << "queue is null" << endl;
exit(EXIT_FAILURE);
}
while (!data1.empty()) {
data2.push(data1.top());
data1.pop();
}
int out = data2.top();
while (!data2.empty()) {
data1.push(data2.top());
data2.pop();
}
return out;
}
bool empty() {
return data1.empty();
}
private:
stack<int> data1;
stack<int> data2;
};
class Stack {
public:
void pop() {
if (data1.empty()) {
cout << "Stack is empty!" << endl;
return;
}
while (data1.size()>1) {
data2.push(data1.front());
data1.pop();
}
data1.pop();
while (!data2.empty()) {
data1.push(data2.front());
data2.pop();
}
}
void push(int temp) {
data1.push(temp);
}
int top() {
if (data1.empty()) {
cout << "Stack is empty!" << endl;
exit(EXIT_FAILURE);
}
while (data1.size() > 1) {
data2.push(data1.front());
data1.pop();
}
int out = data1.front();
data2.push(data1.front());
data1.pop();
while (!data2.empty()) {
data1.push(data2.front());
data2.pop();
}
return out;
}
bool empty() {
return data1.empty();
}
private:
queue<int> data1;
queue<int> data2;
};
int main() {
Queue q;
for (int i = 0; i < 10; i++)
q.push(i);
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
Stack s;
for (int i = 0; i < 10; i++)
s.push(i);
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
最后
以上就是如意萝莉为你收集整理的c++利用栈实现队列和利用队列实现栈的全部内容,希望文章能够帮你解决c++利用栈实现队列和利用队列实现栈所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复