两个栈实现队列的进队列,出队列

#include
#include
using namespace std;
//两个栈模拟队列的进站出站
stack s1;
stack s2;
//s2为空则直接插入,s2不空则将s2中的所有元素压入s1,再将新的元素压入s1
int pop() {
	if (s2.empty()) {
		while (!s1.empty()) {
			int val = s1.top();
			s1.pop();
			s2.push(val);
		}
	}
	if (s2.empty()) {
		return -1;
	}
	int val = s2.top();
	s2.pop();
	return val;
}
//如果s2不空,直接取值。如果s2空先将s1的左右元素压入s1,再从s2取值
void push(int t) {
	while (!s2.empty()) {
		int val = s2.top();
		s2.pop();
		s1.push(val);
	}
	s1.push(t);
	
}

int main() {
	push(1);
	push(2);
	push(3);
	push(4);
	push(5);
	int c = pop();
	cout << c << endl;
	push(6);
	int c2 = pop();
	cout << c2 << endl;
	int c3 = pop();
	cout << c3 << endl;
	int c4 = pop();
	cout << c4 << endl;
	int c5 = pop();
	cout << c5 << endl;
	int c6 = pop();
	cout << c6 << endl;
	return 0;
}

 

你可能感兴趣的:(数据结构与算法)