zoukankan      html  css  js  c++  java
  • 用两个栈实现队列(python/c++)

    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
    # -*- coding:utf-8 -*-
    class Solution:
        def __init__(self):
            self.stack1 = []   #用来入队
            self.stack2 = []   #用来出队
            #将内容先push进一个栈stack1,
            #判断stack2是否为空,空:将栈stack1中的元素pop(删除并返回数组的最后一个元素)
            #并push进stack2,非空:直接出栈
            #出栈时,先push进stack1先从stack2出来,即:实现了先进先出
        def push(self, node):
            # write code here
            self.stack1.append(node)    #入队
        def pop(self):
            # return xx
            if self.stack2:    #如果stack2有元素,直接出队
                return self.stack2.pop()
            while self.stack1:  #当stack2没有元素时,将stack1的元素逆序存入到stack2中
                self.stack2.append(self.stack1.pop())
            return self.stack2.pop() 
    

     

    #include<iostream>
    #include<stack>
    #include<queue>
    using namespace std;
    class Solution
    {
    public:
    	void push(int node)
    	{
    		stack1.push(node);
    	}
    	int pop()
    	{
    		int tmp;
    		if (stack2.empty())
    		{
    			while (!stack1.empty())
    			{
    				tmp = stack1.top();
    				stack2.push(tmp);
    				stack1.pop();
    			}
    		}
    		tmp = stack2.top();
    		stack2.pop();
    		return tmp;
    	}
    private:
    	stack<int> stack1;
    	stack<int> stack2;
    };
    int main()
    {
    	Solution *s = new Solution();
    	for (int i = 0; i<10; i++)
    	{
    		s->push(i);
    		if (i == 5)
    		{
    			s->pop();
    			cout << s->pop() << endl;
    		}
    	}
    
    	system("pause");
    	return 0;
    }
    

      

     

  • 相关阅读:
    谷歌地图地理解析和反解析geocode.geocoder详解(转)
    Html5 Geolocation获取地理位置信息(转)
    利用单片机快速实现家庭智能控制平台
    邪恶改装:TPYBoard制作廉价WIFI干扰器
    [TPYBoard
    [TPYBoard
    [TPYBoard
    python中的subprocess.Popen()使用
    KVM虚拟机的xml配置文件
    Linux LVM 总结
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/10431905.html
Copyright © 2011-2022 走看看