java用棧實現隊列,leetcode 232. 用棧實現隊列(Implement Queue using Stacks)

 2023-10-21 阅读 20 评论 0

摘要:目錄 題目描述:示例:說明:解法: 題目描述: 使用棧實現隊列的下列操作: push(x) -- 將一個元素放入隊列的尾部。pop() -- 從隊列首部移除元素。peek() -- 返回隊列首部的元素。empty() -- 返回隊列是否為空。示例: MyQueue queue = new MyQue

目錄

  • 題目描述:
  • 示例:
  • 說明:
  • 解法:

題目描述:

使用棧實現隊列的下列操作:

  • push(x) -- 將一個元素放入隊列的尾部。
  • pop() -- 從隊列首部移除元素。
  • peek() -- 返回隊列首部的元素。
  • empty() -- 返回隊列是否為空。

示例:

    MyQueue queue = new MyQueue();queue.push(1);queue.push(2);  queue.peek();  // 返回 1queue.pop();   // 返回 1queue.empty(); // 返回 false

說明:

  • 你只能使用標準的棧操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
  • 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。

解法:

class MyQueue {
public:/** Initialize your data structure here. */stack<int> stk;MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stk.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {stack<int> tmp;while(!stk.empty()){tmp.push(stk.top());stk.pop();}int res = tmp.top();tmp.pop();while(!tmp.empty()){stk.push(tmp.top());tmp.pop();}return res;}/** Get the front element. */int peek() {stack<int> tmp;while(!stk.empty()){tmp.push(stk.top());stk.pop();}int res = tmp.top();while(!tmp.empty()){stk.push(tmp.top());tmp.pop();}return res;}/** Returns whether the queue is empty. */bool empty() {return stk.empty();}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj = new MyQueue();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.peek();* bool param_4 = obj.empty();*/

轉載于:https://www.cnblogs.com/zhanzq/p/10571156.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/154594.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息