zoukankan      html  css  js  c++  java
  • leetcode-232

     Implement Queue using Stacks

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.

    题目的大概意思就是让我们用栈实现队列的相关功能。Stack是java里面已经写好的栈类可以直接使用。

    java代码:

    public class MyQueue{
    	Stack<Integer> queue=new Stack<Integer>();
    	public void push(int x){
    		Stack<Integer> temp=new Stack<Integer>();
    		while(!queue.empty()){
    			temp.push(queue.pop());
    		}
    		queue.push(x);
    		while(!temp.empty()){
    			queue.push(temp.pop());
    		}
    	}
    	public int pop(){
    		return queue.pop();
    	}
    	public int peek(){
    		return queue.peek();
    	}
    	public boolean empty(){
    		return queue.empty();
    	}
    	
    }
    

      

  • 相关阅读:
    K好数
    蓝桥杯 安慰奶牛
    蓝桥杯 节点选择
    模拟链表
    10588
    八数码的 八种境界
    HIT 2051
    概率DP
    数组越界溢出
    FATFS在SD卡里,写入多行数据出的问题
  • 原文地址:https://www.cnblogs.com/lcbg/p/6567174.html
Copyright © 2011-2022 走看看