每日一题--两个栈实现一个队列(Google推荐面试书--Cracking the Coding Interview)

题目

  • 原文:
    Implement a StackQueue class which implements a queue using two stacks.
  • 译文:
    使用两个栈实现一个队列StackQueue。

分析

  1. 这里代码设计两个栈最大长度等长,当然也可以不等长;
  2. 将两个栈功能上划分为一个负责入栈(m_sin),一个负责出栈(m_sout);
  3. 入队列时,直接将元素压入m_sin,当m_sin栈满但m_sout栈未满时,先将m_sin中的元素出栈并压入m_sout,留出位置入栈;
  4. 出队列时,若m_sout栈非空直接从m_sout出栈,否则先将m_sin中的元素出栈并压入m_sout。
  5. 取队顶元素时,若m_sout栈非空直接从m_sout栈顶取,否则先将m_sin中的元素出栈并压入m_sout。
  6. 取队尾元素时,若m_sin栈非空直接从m_sin栈顶取,否则先将m_sout中的元素出栈并压入m_sin。
  • 实际上,可以将两个栈看成是将一个队列从中间切开后,m_sin栈从栈顶到栈底对应队列的队尾到切开处, m_sout栈从栈顶到栈底对应队列的队首到切开处。

代码

#include<iostream>
#include<stack>
using namespace std;

template <typename T>

class StackQueue {
	public:
		StackQueue(int MaxStackSize) {
			this->maxStacksize = MaxStackSize;
		}
		~StackQueue() {	
		}
		
		void push(T node) {
			if(m_sin.size() >= maxStacksize && m_sout.size() >= maxStacksize) {
				cout << "队列已满,无法入队!" << endl; 
				return;
			}
			if(m_sin.size() >= maxStacksize) {
				move(m_sin, m_sout);
			}			
			m_sin.push(node);
			cout << "入队列为" << m_sin.top() << ",成功。" << endl; 		
		}
		
		void pop() {
			move(m_sin, m_sout);
			if(m_sout.empty()) {
				cout << "队列已空,无法出队!" << endl; 
			}
			else {
				cout << "出队列为" << m_sout.top() << ",成功。" << endl; 
				m_sout.pop();
			}		
		}
		
		T* front() {
			if (m_sin.empty() && m_sout.empty()) {
				cout << "当前队已空!" << endl;
				return NULL; 
			}
			
			move(m_sin, m_sout);
			//cout << "队列头为" << m_sout.top() << endl;
			return &m_sout.top();
		}
		
		T* back() {
			if (m_sin.empty() && m_sout.empty()) {
				cout << "当前队已空!" << endl;
				return 	NULL; 
			}
			
			move(m_sout, m_sin);
			//cout << "队列尾为" << m_sin.top() << endl; 
			return &m_sin.top();
		}
		
		int size() {
			return m_sin.size() + m_sout.size();
		}
		
		bool empty() {
			return m_sin.empty() && m_sout.empty();
		}
		
		void move(stack<T> &ssrc, stack<T> &sdst) {
			if(sdst.empty() && !ssrc.empty()) {
				while(!ssrc.empty() && sdst.size() < maxStacksize) {
					T node = ssrc.top();
					ssrc.pop();
					sdst.push(node);
				}
			}
		}
		
	private:
		stack<T> m_sin, m_sout;
		int maxStacksize;
};

int main() {
	StackQueue<int> queue(2);
	queue.push(1);
	queue.push(2);
	queue.push(3);
	cout << "当前队列长度为:" << queue.size() << endl;
	int *pqback = queue.back();
	cout << "当前队尾是" <<  *pqback << endl;
	queue.push(4);
	queue.push(5);
	int *pqfront = queue.front();
	cout << "当前队头是" <<  *pqfront << endl;
	queue.front();
	queue.pop();
	queue.pop();
	queue.push(5);
	pqback = queue.back();
	cout << "当前队尾是" <<  *pqback << endl;	
	queue.pop();
	queue.pop();
	cout << "当前队空:" << queue.empty() << " (1-true;0-false)" << endl;
	cout << "当前队列长度为:" << queue.size() << endl;
	queue.pop();
	queue.front();
}

结果展示
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39860046/article/details/87975041