• 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.

    Notes:

      • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
      • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
      • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    链接: http://leetcode.com/problems/implement-queue-using-stacks/

    2/28/2017

     1 public class MyQueue {
     2     Stack<Integer> s;
     3     Stack<Integer> t;    
     4     /** Initialize your data structure here. */
     5     public MyQueue() {
     6         s = new Stack<Integer>();
     7         t = new Stack<Integer>();    
     8     }
     9     
    10     /** Push element x to the back of queue. */
    11     public void push(int x) {
    12         if (s.isEmpty()) s.push(x);
    13         else {
    14             while (!s.isEmpty()) {
    15                 t.push(s.pop());
    16             }
    17             s.push(x);
    18             while (!t.isEmpty()) {
    19                 s.push(t.pop());
    20             }
    21         }        
    22     }
    23     
    24     /** Removes the element from in front of queue and returns that element. */
    25     public int pop() {
    26         return s.pop();        
    27     }
    28     
    29     /** Get the front element. */
    30     public int peek() {
    31         return s.peek();        
    32     }
    33     
    34     /** Returns whether the queue is empty. */
    35     public boolean empty() {
    36        return s.isEmpty();        
    37     }
    38 }
  • 相关阅读:
    简单理解OOP——面向对象编程
    SpringMVC拦截器
    Vue简洁及基本用法
    springMVC实现文件上传下载
    Python笔记⑤爬虫
    Python笔记4
    Python笔记3
    Python基础语法笔记2
    Python基础入门语法1
    Navicat连接mysql时候出现1251错误代码
  • 原文地址:https://www.cnblogs.com/panini/p/6482241.html
Copyright © 2020-2023  润新知