• Implement Stack using Queues 用队列实现栈


    Implement the following operations of a stack using queues.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.

    • empty() -- Return whether the stack is empty.
    解题思路:
    用队列实现栈的操作。包含输入、输出、取栈顶元素、推断栈是否为空。
    我们知道,栈是先进后出的容器,队列是先进先出的容器。所以输入元素非常easy,可是输出元素不是输出队列的front,而是back元素。删掉back元素。此时我们能够将队列1中的非队尾元素存在另外一个队列2中,删掉之前队列的最后一个元素不另行存储即可。

    此时队列2中有元素。是可运行的容器。队列1是空,备用容器,所以我们须要两个表示符,代表两个队列,表示此队列是否是当前可操作的容器。简单来讲,就是用两个队列的操作(push()。pop(),empty())来实现栈的各种操作。


    完整可运行代码例如以下:

    #include<iostream>
    #include<queue>
    using namespace std;
    queue<int> qu1;
    queue<int> qu2;
    bool qu1_use=1;
    bool qu2_use=0;
    void push(int x);
    void pop() ;
    int top() ;
    bool empty() ;
    void main()
    {
    	push(1);
    	push(2);
    	push(3);
    	push(4);
    	int i=5;
    	while(i)
    	{
    		if(!empty())
    		{
    			cout<<top()<<endl;
    			pop();
    		}
    		i--;
    	}
    	
    }
    void push(int x)
    {
    	if(qu1_use==1)
    	{
    		qu1.push(x);
    	}
    	else
    		qu2.push(x);
    }
    void pop() 
    {
    	if(qu1.empty()&&qu2.empty())
    		exit(0);
    	if(qu1_use==1&&!qu1.empty())
    	{
    		while(qu1.size()>1)
    		{
    			qu2.push(qu1.front());
    		    qu1.pop();
    		}
    		qu1.pop();
    		qu1_use=0;
    		qu2_use=1;
    		return;
    	}
    	if(qu2_use==1&&!qu2.empty())
    	{
    		while(qu2.size()>1)
    		{
    			qu1.push(qu2.front());
    		    qu2.pop();
    		}
    		qu2.pop();
    		qu1_use=1;
    		qu2_use=0;
    		return;
    	}   
    	return;
    }
    
    int top() 
    {
    	
    	if(qu1_use==1&&!qu1.empty())
    	{
    		return qu1.back();
    	}
    	if(qu2_use==1&&!qu2.empty())
    	{
    		return qu2.back();
    	}   
    	//if(qu1.empty()&&qu2.empty())
    	exit(0);    
    }
    
    bool empty() 
    {
    	if((qu1_use==1&&qu1.empty())||(qu2_use==1&&qu2.empty()))
    	{
    		cout<<"empty!"<<endl;
    		return true;
    	}
    		
    	else return false;
    }

    运行上面代码得到结果为:
    4
    3
    2
    1
    empty!

  • 相关阅读:
    解决方法 svn checkout 更改用户名密码/断网续传
    解决方法 cannot be resolved as a type
    解决方法 Syntax error on token "enum", invalid Expression
    使用笔记 Sublime text 持更
    解决方法 cvs或svn上下载的新项目无build path
    解决方法 卸载jdk以及重新安装jdk
    配置笔记 eclipse, jdk, tomcat, maven, mysql, alt+/
    ubantu配置java环境变量
    写给自己的!
    数据设计模式
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/6956624.html
Copyright © 2020-2023  润新知