微软面试100题-57 (用俩个栈实现队列)

来源:互联网 发布:乔杉咖啡厅网络剧 编辑:程序博客网 时间:2024/06/05 14:29

57.用俩个栈实现队列(栈、队列)。

题目:某队列的声明如下:

template class CQueue
{
public:
      CQueue() {}
      ~CQueue() {}

      void appendTail(const T& node);  // append a element to tail
      void deleteHead();               // remove a element from head

private:
     T> m_stack1;
     T> m_stack2;
};

分析:从上面的类的声明中,我们发现在队列中有两个栈。
因此这道题实质上是要求我们用两个栈来实现一个队列。
相信大家对栈和队列的基本性质都非常了解了:栈是一种后入先出的数据容器,
因此对队列进行的插入和删除操作都是在栈顶上进行;队列是一种先入先出的数据容器,
我们总是把新元素插入到队列的尾部,而从队列的头部删除元素。

关键是只有当S2为空时,才将S1插入S2.

package com.interview.algorithm;import java.util.Queue;import java.util.Stack;public class StackToQueue {Stack s1= new Stack();Stack s2 = new Stack();public void add(int e){s1.push(e);}public int remove() throws Exception{if(s1.isEmpty() && s2.isEmpty())throw new Exception("Queue is empty.");if(s2.isEmpty()){while(!s1.isEmpty()){s2.add(s1.pop());}}return (Integer) s2.pop();}public int size(){return s1.size() + s2.size();} public static void main(String[] args) throws Exception {// TODO Auto-generated method stubStackToQueue q = new StackToQueue();q.add(1);q.add(3);q.add(5);System.out.print(q.remove());q.add(2);q.add(4);System.out.print(q.remove());System.out.print(q.remove());System.out.print(q.remove());}}

0 0
原创粉丝点击