【leetcode】232. Implement Queue using Stacks

来源:互联网 发布:淘宝纸箱设备 编辑:程序博客网 时间:2024/06/05 04:15

一、题目描述

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 emptyoperations 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,移除函数pop,堆栈大小size,堆栈是否为空empty


思路:两个堆栈实现一个队列

(1)队列添加元素:进栈p1,

(2)队列删除元素:如果栈p2不空,直接删除p2的栈顶元素;如果栈p2空,先从p1把所有元素出栈进栈到p2,然后再删除p2的栈顶元素。

(3)返回队列队头元素:如果栈p2不空,直接返回p2的栈顶元素;如果栈p2空,先从p1把所有元素出栈进栈到p2,然后再返回p2的栈顶元素。

(4)判断队列是否为空:判断栈p1和p2是否为空。


c++代码(0ms,10.84%)

class Queue {public:    stack<int> p1,p2;    // Push element x to the back of queue.    void push(int x) {        p1.push(x);    }    // Removes the element from in front of queue.    void pop(void) {        if(p2.empty()){            while(!p1.empty()){                p2.push(p1.top());                p1.pop();            }        }        p2.pop();    }    // Get the front element.    int peek(void) {        if(p2.empty()){            while(!p1.empty()){                p2.push(p1.top());                p1.pop();            }        }        return p2.top();    }    // Return whether the queue is empty.    bool empty(void) {        return p1.empty() && p2.empty();    }};


0 0
原创粉丝点击