严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Intel 电面:用队列实现栈。我开始问几个队列面试官说几个都行。我先用2个队列做完。 让优化用一个队列如何实现

Go down

Intel 电面:用队列实现栈。我开始问几个队列面试官说几个都行。我先用2个队列做完。 让优化用一个队列如何实现 Empty Intel 电面:用队列实现栈。我开始问几个队列面试官说几个都行。我先用2个队列做完。 让优化用一个队列如何实现

Post by Admin Mon Oct 23, 2017 7:43 pm

public class Queue2Stack {
   /**
    * 用队列的入队和出队
    * 来实现栈的入栈和出栈
    * */
   
   Queue queue1 = new Queue();//主要存放数据
   Queue queue2 = new Queue();//辅助
   
   public void push(Object o) {
       queue1.add(o);
   }
   
   public Object pop() {
       Object o = null;
       while(queue1.length()>1) {
           queue2.add(queue1.poll());
       }
       if(queue1.length()==1) {
           o = queue1.poll();
           while(queue2.length()>0) {
               queue1.add(queue2.poll());
           }
       }
       
       return o;
   }
   
   public int length() {
       return queue1.length();
   }
   


-----------------------------
优化:  如何只用一个队列实现栈


有两个队列的时候我们需要将元素循环从队列A移到队列B,但如果只有一个队列A呢? 我们可以将元素从队列A取出,然后再放入队列A,具体算法为:
push:
(1) 将元素加入队列A
pop:
(1) 将队列A中 size-1 个元素循环取出,再次加入队列A
(2) 将当前队首元素取出并返回
C++ 代码为:
[cpp] view plain copy
class myStack {  
private:  
 queue<int> que;  
public:  
 void push(int x) {  
   que.push(x);  
 }  
 
 int pop() {  
   int size = que.size();  
   assert(size >= 1);  
 
   for (int i = 0; i < size-1; i++) {  
     que.push(que.front());  
     que.pop();  
   }  
 
   // if we only want to check the top value, we need to add "que.push(x)"  
   // after "que.pop()"  
   int x = que.front(); que.pop();  
   return x;  
 }  
 
};

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum