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 top, peek/pop from top, size, 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).
    

译:使用栈来实现一个拥有以下操作的队列:

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

注意:
你必须仅仅使用标准的栈操作,意味着存在这几个可用的操作:push到栈顶,从栈顶peek/pop,size和is empty操作

问题分析
先画图,画分解图一步步的通过入栈出栈LIFO的特性就能反推出链表FIFO的行为,例如存在两个栈A 、B,将一组元素{a, b, c, d, e, f, g, h} 进行各种链表操作,只要遵循FIFO的行为就不难理解。

你可能感兴趣的:(232. Implement Queue using Stacks)