用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。


// test14.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
#include<stack>
using namespace std;

class Solution
{
public:
	void push(int node) {
		while (!stack2.empty())//入隊時,要保證stack2為空
		{
			stack1.push(stack2.top());
			stack2.pop();
		}
		stack1.push(node);
		cout << "入隊元素是:" <<stack1.top()<< endl;
	}

	int pop() {
		
		while(!stack1.empty())//出隊時,要保證stack1為空
		{
			stack2.push(stack1.top());
			stack1.pop();
		}
		cout << "出隊元素是:" << stack2.top() << endl;
		int temp = stack2.top();
		stack2.pop();
		return temp;
	}

private:
	stack<int> stack1;//作為入隊序列
	stack<int> stack2;//作為出隊序列
};

int main()
{
	
	Solution so;
	so.push(1);
	so.push(2);
	so.push(3);

	
	so.pop();
	so.pop();
	so.push(4);
	so.pop();
	so.push(5);
	so.pop();
	so.pop();
	
	cout << endl;
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM