前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-225-Implement Stack using Queues

leetcode-225-Implement Stack using Queues

作者头像
chenjx85
发布2019-03-14 17:16:07
3930
发布2019-03-14 17:16:07
举报

题目描述:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

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

要完成的函数:

void push(int x) 

int pop() 要求返回被弹出的元素值

int top() 

bool empty() 

说明:

1、这道题目要求用队列来实现堆栈,要求只能使用队列的push pop front size empty这几个函数,完成堆栈的压入、弹出、栈顶元素和判断是否为空的功能。

2、队列与堆栈的唯一不同之处,在于堆栈是队尾输入、队尾输出,队列是队尾输入、队首输出,所以如果我们把输入的新元素放在队首,是不是就可以用队列完成堆栈了?

代码如下:(附详解)

代码语言:javascript
复制
    queue<int>q1;//定义一个队列
    
    /** Push element x onto stack. */
    void push(int x) 
    {
        q1.push(x);
        for(int i=0;i<q1.size()-1;i++)//对于每个队中已有元素,取出之后插到队尾,保证新元素在前,旧元素在后
        {
            q1.push(q1.front());
            q1.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() //返回元素值
    {
        int t=q1.front();
        q1.pop();
        return t;
    }
    
    /** Get the top element. */
    int top() 
    {
        return q1.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        return q1.empty();
    }

上述代码实测2ms,beats 100% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档