用栈实现队列

来源:互联网 发布:去年淘宝双11销售额 编辑:程序博客网 时间:2024/04/29 09:23
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。


样例

比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2

import java.util.Stack;/** * 正如标题所述,你需要使用两个栈来实现队列的一些操作。队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。pop和top方法都应该返回第一个元素的值。样例比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2 *  * @author Dell * */class MyQueue{  private Stack<Integer> stack1;  private Stack<Integer> stack2;  public MyQueue()  {  stack1=new Stack<>();  stack2=new Stack<>();  }  public void push(int element)  {  stack1.push(element);    }  public int pop()  {    int value=0;  if(stack2.isEmpty()!=true)  {  value=stack2.pop();  return value;  }  else if(stack1.isEmpty()!=true)  {  while(stack1.isEmpty()!=true)  {  stack2.push(stack1.pop());   }   value=stack2.pop();  return value;  }  else  {  return value;  }  }  public int top(){   int result=0;   if(stack2.isEmpty()!=true)   {   result=stack2.peek();   return result;   }   else if(stack1.isEmpty()!=true){  while(stack1.isEmpty()!=true){  stack2.push(stack1.pop()); }   result=stack2.peek();  return result;  }   else   {      return result;   }}}public class Test40 {public static void main(String[] args) {MyQueue q=new MyQueue();q.push(1);System.out.println(q.pop());q.push(2);q.push(3);System.out.println(q.top());System.out.println(q.pop());}}


原创粉丝点击