首页 > 试题广场 >

用你熟悉的语言编写程序用两个栈(Stack)模拟队列(Que

[问答题]
用你熟悉的语言编写程序用两个栈(Stack)模拟队列(Queue)的先进先出操作,仅实现add、remove方法即可。
1)请先描述思路; 2)编写完整代码实现,编程语言不限。
思路:把栈比喻成水杯,将A水杯中的水倒入B水杯中(不考虑水的流动性),之前A水杯中最下面的水就会在B水杯中的最上面,就实现了队列的先进先出原则。
代码如下:
import java.util.Stack;
public class StackToQueue {
    static Stack<Integer> stack1 = new Stack<Integer>();
    static Stack<Integer> stack2 = new Stack<Integer>();
    
    public void add(int node) {
        stack1.push(node);
    }
    
    public int remove() {
    	if(stack2.isEmpty()){//pop时如果stack2为空则将stack1内元素倒置入stack2,取栈顶元素;
	    	while(!stack1.isEmpty()){
	            stack2.push(stack1.pop());
	        }
    	}
        return stack2.pop();
    }
}
望采纳!
编辑于 2015-09-18 17:14:43 回复(2)
思路:已知栈是后进先出的性质,两个基本操作上push和pop; 已知队列的基本操作上add和remonv; 为了完成两个栈实现一个队列(先进先出)的功能,可以定义两个栈,一个命名为入栈,另外一个则命名为出栈. add的实现则只需要将值压进入栈即可;remove的实现则需要先判断出栈是否为空,如果为空则需要把入栈的内容依次弹出压入到出栈,然后弹出出栈栈顶的元素即可。
template<class T>
class MyQueue                //自定义的MyQueue类
{
public:
	void Add(T data);    //自定义队列的增加功能
	void Remove(T data); //自定义队列的删除功能
private:
	T front();
	T end();
private:
	stack<T> stackIn;     //入栈 
        stack<T> stackOut;  //出栈 };

template<class T>
void MyQueue<T>::Remove(T data)
{
	if (stackOut.empty())
	{
		while (!stackIn.empty())
		{
			stackOut.push(stackIn.top());
			stackIn.pop;
		}
	}
	if (!stackOut.empty())
	{
		stackOut.pop();
	}
	
}

template<class T>
void MyQueue<T>::Add(T data)
{
	stackIn.push(data);
} 


发表于 2015-09-10 21:29:08 回复(0)
思路:栈是先进后出,队列是先进先出。把两个栈串联,就是 先进后出-后出先出,即先进先出,类似于把一个物体倒置两次就是正放的原理一样。
代码实现:
public class StackToQueue {
       private  static Stack<Object> preStack=new Stack<>();
private static Stack<Object> nextStack=new Stack<>();
public void add(Object node){
preStack.push(node);
}
public Object remove(){
if(nextStack.isEmpty()){
while(!preStack.isEmpty()){
nextStack.push(preStack.pop());
}
}
if(nextStack.isEmpty()){
return null;
}else{
return nextStack.pop();
}
}
发表于 2016-09-06 19:28:18 回复(0)
创建两个int类型的栈,s1和s2
做入队操作时,先检查s1是否为空,如果为空,则将s2栈中内容分别出栈,再压栈如s1。然后再将要添加的元素压入s1中。
做出队操作时,先检查s2是否为空,如果为空,则将s1栈中内容分别出栈,再压栈如s2。然后再将s2中的栈顶元素出栈,作为出队元素。
move方法中描述了两个栈相互转移的过程。

private Stack<int> s1,s2;

void add(int value)
{
    if(s1.empty())
    {
        move (s2,s1);
    }
    s1.push(s1);
}

int remove()
{
    int result=0;
    if(s2.empty())
    {
        move(s1,s2);
    }

    if(s2.empty())
    {
        return null;
    }
    result=s2.top();
     s2.pop();
     return result;
}

void move(Stack<int> s,Stak<int> t)
{
    int tmp=0;
    wile(!s.empty())
    {
        tmp=s.pop();
        t.push(tmp);
    }
}
发表于 2015-08-11 15:15:21 回复(1)
template <typename T>
class MyQueue
{
public:
   void push(T);
   void pop();   
private:
stack <T> s1;
    stack <T> s2;
};

template <typename T>
void MyQueue<T>::push(T t)
{
  s1.push(t);
}
template <typename T>
void MyQueue<T>::pop()
{
  if(s2.size() != 0)
 s2.pop();
  else
  {
if(s1.size() != 0)
{
while(s1.size() != 0)
{
     s2.push(s1.top());
     s1.pop();  
}
}
     else
{
std::cout<<"队列是空"<<std::endl;
}
    
s2.pop();

  }
  
}

发表于 2015-07-12 16:52:34 回复(0)
public class QueueWithTwoStack { static Stack<Integer> s1 = new Stack<Integer>(); static Stack<Integer> s2 = new Stack<Integer>(); public boolean add(int v){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } s1.push(v); return true; }else { if(s1.size() < 20){ s1.push(v); return true; }else{ if (s2.isEmpty()) { while(!s1.isEmpty()){ s2.push(s1.pop()); } s1.push(v); return true; }else{ System.out.println("queue is full"); return false; } } } } public int remove(){ if(!s2.isEmpty()) return s2.pop(); else { while(!s1.isEmpty()){ s2.push(s1.pop()); } return s2.pop(); } } public static void main(String[] args) { QueueWithTwoStack myQueue = new QueueWithTwoStack(); for(int i = 0; i < 21; i ++){ if(myQueue.add(i)) System.out.print(i + " "); } System.out.println(); for(int i = 0; i < 10; i ++){ System.out.print(myQueue.remove() + " ");//前10个 } if(myQueue.add(21)) System.out.print(21 + " "); if(myQueue.add(22)) System.out.print(22 + " "); if(myQueue.add(23)) System.out.print(23 + " "); for(int i = 0; i < 14; i ++){ System.out.print(myQueue.remove() + " ");//后13个 } } }
发表于 2014-10-12 18:04:04 回复(1)
package StackAndQueue;

import java.util.Stack;

public class Main {
    private Stack<Integer> stackIn = null;
    private Stack<Integer> stackOut = null;

    public Main() {
        stackIn = new Stack<Integer>();
        stackOut = new Stack<Integer>();
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.add(1);
        main.add(2);
        main.add(3);
        main.add(4);
        main.add(5);
        main.add(6);
        main.add(7);
        main.add(8);
        main.remove();
        main.remove();
        main.remove();
        main.remove();
        main.remove();
        main.remove();
        main.remove();
        main.remove();
    }
    
    public void add(int i) {
        Integer push = (Integer) this.stackIn.push(new Integer(i));
        System.out.println("元素 " + push + " 已进入队列");
        System.out.println(stackIn);
    }

    public void remove() {
        if (stackIn.isEmpty()) {
            System.out.println("队列已空");
            return;
        }
        while (!stackIn.isEmpty()) {
            stackOut.push(stackIn.pop());
        }
        Integer pop = (Integer) stackOut.pop();
        System.out.println("元素 " + pop + " 已退出队列");
        while (!stackOut.isEmpty()) {
            stackIn.push(stackOut.pop());
        }
        System.out.println(stackIn);
    }

}

发表于 2021-03-13 09:48:16 回复(0)
#include<iostream>
#include<string>
#include<stack>
#include<algoritnm>
using namespace std;
template<class T>
class Queue
{
public:
    void add(T elem);
    T remove();
private:
    stack<T>  stack1;
    stack<T>  stack2;
}
template<class T>
void Queue::add(elem){
    stack1.push(elem);    
}
template<class T>
T Queue::remove(){
    if(stack2.empty())
    {
        if(stack1.empty()){
            exit(-1);
        }else
        {
            while(!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
    }
    return stack2.pop();
}
int main(){
    Queue<int>  q;
    for(int i=1;i<=9;i++)
            q.add(i*10);
    for(int i=1;i<=9;i++){
        cout<<q.remove()<<" ";
    }
    cout<<endl;
    return 0;
}

发表于 2016-06-16 15:44:54 回复(0)
用两个栈实现一个队列的功能?要求给出算法和思路!

<分析>:

入队:将元素进栈A

出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;

如果不为空,栈B直接出栈。
void N_queue::N_push(int a)
{
 st1.push(a);
}
int N_queue::N_pop()
{
 int a;
 if(st2.empty())
 {
  while (!st1.empty())
  {
   a=st1.top();
   st2.push(a);
   st1.pop();
  }
 }
 a=st2.top();
 st2.pop();
 return a;
}
bool N_queue::N_empty()
{
 return st1.empty()&&st2.empty();
}

用两个队列实现一个栈的功能?要求给出算法和思路!

<分析>:

入栈:将元素进队列A

出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列,否则将队列A中的元素 以此出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把 队列B中的元素出队列以此放入队列A中。

void N_stack::N_push(int a)
{
 qu1.push(a);
}
int N_stack::N_pop()
{
 int a,b;
 while(qu1.size()>1)
 {
  a=qu1.front();
  qu2.push(a);
  qu1.pop();
 }
 b=qu1.front();
 qu1.pop();
 while(!qu2.empty())
 {
  a=qu2.front();
  qu1.push(a);
  qu2.pop();
 }
 return b;
}
bool N_stack::N_empty()
{
 return qu1.empty();
}
发表于 2015-09-18 11:38:50 回复(0)
<div> #include &lt;iostream&gt; </div> <div> #include &lt;stack&gt; </div> <div> using namespace std; </div> <div> stack&lt;int&gt; stack1; </div> <div> stack&lt;int&gt; stack2; </div> <div> <br /> </div> <div> void queue_add(int data) </div> <div> { </div> <div> <span> </span>stack1.push(data); </div> <div> } </div> <div> void queue_remove(int *data) </div> <div> { </div> <div> <span> </span>if (!stack2.empty()) </div> <div> <span> </span>{ </div> <div> <span> </span>*data=stack2.top(); </div> <div> <span> </span>stack2.pop(); </div> <div> <span> </span>} </div> <div> <span> </span>else{ </div> <div> <span> </span>while (stack1.size()&gt;0) </div> <div> <span> </span>{ </div> <div> <span> </span>int temp=stack1.top(); </div> <div> <span> </span>stack1.pop(); </div> <div> <span> </span>stack2.push(temp); </div> <div> <span> </span>} </div> <div> <span> </span>if (stack2.size()&gt;=0) </div> <div> <span> </span>{ </div> <div> <span> </span>*data=stack2.top(); </div> <div> <span> </span>stack2.pop(); </div> <div> <span> </span>} </div> <div> <span> </span>} </div> <div> } </div> <div> int main() </div> <div> { </div> <div> <span> </span>int data; </div> <div> <span> </span>queue_add(1); </div> <div> <span> </span>queue_add(2); </div> <div> <span> </span>queue_remove(&amp;data); </div> <div> <span> </span>printf("%d\n",data); </div> <div> <br /> </div> <div> <br /> </div> <div> <span> </span>queue_add(3); </div> <div> <span> </span>queue_add(4); </div> <div> <span> </span>queue_add(5); </div> <div> <br /> </div> <div> <span> </span>queue_remove(&amp;data); </div> <div> <span> </span>printf("%d\n",data); </div> <div> <span> </span>queue_remove(&amp;data); </div> <div> <span> </span>printf("%d\n",data); </div> <div> <span> </span>queue_remove(&amp;data); </div> <div> <span> </span>printf("%d\n",data); </div> <div> <span> </span>queue_remove(&amp;data); </div> <div> <span> </span>printf("%d\n",data); </div> <pre class="prettyprint lang-cpp">}</pre> <br />
发表于 2015-09-11 22:13:27 回复(0)
<pre class="prettyprint lang-java">/** 思路: 1)两个栈一个作为入栈,一个作为出栈,记为STACK1和STACK2; 2)add操作是将数字压入到STACK1中,若此时STACK1满,则操作失败(注:java中使用Stack类,不会出现栈满情况); 3)remove操作是从STACK2中弹出一个数字,当STACK2为空时,从STACK1中将数据全部弹出并压入后,再进行弹出动作; 若此时STACK2还为空,则操作失败; */ //假设队列的元素均为整型; import java.util.*; public class Queue{ Stack&lt;Integer&gt; stack1 = new Stack&lt;Integer&gt;(); <span>Stack&lt;Integer&gt; stack2 = new Stack&lt;Integer&gt;(); &nbsp; public void add(int a){ stack1.push(a); } public int remove(int a){ if(stack2.isEmpty() == true){ while(stack1.isEmpty() != true){ stack2.push(stack1.pop()); } } if(stack2.isEmpty() != true){ return stack2.pop(); } else return -1;//error occured. }</span> }</pre> <br />
发表于 2015-09-11 09:41:53 回复(0)
看了这么多答案.对c++的说句...只有一个人用了template.
题目上没说整数...应该用template
发表于 2015-09-09 11:04:35 回复(0)
<pre class="prettyprint lang-java">//思路:标记这两个栈为firstStack、secondStack,当实现add功能时,往firstStack里添加元素,当实现remove功能时,将secondStack里的第一个元素出栈删除。 public class solution{ Stack&lt;Integer&gt; firstStack=new Stack&lt;Integer&gt;(); <span>Stack&lt;Integer&gt; secondStack=new Stack&lt;Integer&gt;();</span> public static void add(int node){ while(!secondSack.isEmpty()){ firstStack.push(secondStack.pop()); } firstStack.pop(node); } public static boolean remove(){ if(!secondStack.isEmpty()){ <span>secondStack.pop(); &nbsp; return true;</span> }else{ while(!firstStack.isEmpty()){ secondStack.push(firstStack.pop()); } secondStack.pop(); return true; } } }</pre> <div> <span><br /> </span><br /> </div>
发表于 2015-09-07 21:56:45 回复(0)
思路:栈是“先进后出”,队列是“先进先出”,当向队列中加入元素n,m,在队列中n应该位于队尾,当删除时候,元素n最先删除;向栈1中加入元素n、m时,m位于栈顶,将栈1中元素加入到栈2中,则n位于栈2的顶部,当删除时,元素n先删除,即实现了两个栈模拟队列的过程;
     
public class queue{
  private Stack<String> stackOne=new Stack<String>();
  private Stack<String> stackTwo=new Stack<String>();
  
  public void add(String str){
      stackOne.push(str);
  }
  
  public void delete(){
     if(stackTwo.isEmpty()){
        while(!stackOne.isEmpty()){
           stackTwo.push(stackOne.pop());
        }
     }
    if(stackTwo.isEmpty()){
       system.out.printIn("queue is empty");
    }
   else{
        stackTwo.pop();
     }
   
     
 }

   
}
发表于 2015-06-05 14:16:46 回复(0)
那个数组,保证后加的值角标最大,第次只取第一个。
发表于 2014-11-29 13:19:34 回复(0)
xxj头像 xxj
1)两个栈A,B(足够大)
    A只入栈,B只出栈
    当B栈空时,禁止A栈入,禁止B栈出,并将A栈的所有元素一次push到B栈,结束后开启A栈入,开启B栈出
发表于 2014-11-18 15:44:50 回复(0)