• 代码随想录--栈与队列-用队列实现栈


    使用队列实现栈的下列操作:

    • push(x) -- 元素 x 入栈
    • pop() -- 移除栈顶元素
    • top() -- 获取栈顶元素
    • empty() -- 返回栈是否为空

    (这里要强调是单向队列

    用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用

     

    1. import java.util.LinkedList;
    2. import java.util.Queue;
    3. public class Stack {
    4. Queue queue1; // 和栈中保持一样元素的队列
    5. Queue queue2; // 辅助队列
    6. /** Initialize your data structure here. */
    7. public Stack() {
    8. queue1 = new LinkedList<>();
    9. queue2 = new LinkedList<>();
    10. }
    11. /** Push element x onto stack. */
    12. public void push(int x) {
    13. queue2.offer(x); // 先放在辅助队列中
    14. while (!queue1.isEmpty()){
    15. queue2.offer(queue1.poll());
    16. }
    17. Queue queueTemp;
    18. queueTemp = queue1;
    19. queue1 = queue2;
    20. queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
    21. }
    22. /** Removes the element on top of the stack and returns that element. */
    23. public int pop() {
    24. return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可
    25. }
    26. /** Get the top element. */
    27. public int top() {
    28. return queue1.peek();
    29. }
    30. /** Returns whether the stack is empty. */
    31. public boolean empty() {
    32. return queue1.isEmpty();
    33. }
    34. public static void main(String[] args) {
    35. Stack stack = new Stack();
    36. stack.push(1);
    37. stack.push(2);
    38. System.out.println(stack.pop());
    39. System.out.println(stack.top());
    40. System.out.println(stack.empty());
    41. }
    42. }

  • 相关阅读:
    Chrome插件精选 — 暗色主题插件
    Opencv+YOLO-V3实现目标跟踪
    leetcode1358. 包含所有三种字符的子字符串数目
    Ego-Swarm编译与运行
    【TS】基础类型
    【工具流】WSL2安装
    Linux命令教程:使用cat命令查看和处理文件
    扩展实现Unity协程的完整栈跟踪
    AnolisOS8安装Docker
    C#基础教程(十五) Linq
  • 原文地址:https://blog.csdn.net/weixin_56194193/article/details/132910335