一个队列实现栈

本文介绍了一种使用队列实现栈数据结构的方法。通过循环操作,将队列转换为具有栈特性的数据结构,实现了栈的基本操作,包括push、pop、top和empty。文章详细解释了如何通过队列操作达到栈的功能,并提供了Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个队列实现栈

最近学习数据结构,所以leetcode上找些题巩固学习。题目比较简单,但是自己写出来也可以更好的理解队列和栈这种数据结构。

思路

一个队列实现栈的思想就是循环往复,就是将出队的元素再加入到队列中,这样才size-1个循环后便可以得到原本最上面的数据。
在这里插入图片描述
如图,只需循环size-1次就可将3移至队尾,这样我们就可以将3出栈。

如果我们想只是想看一下栈顶,不想出栈,只要再将3添加到最前面即可。
具体代码如下:

import java.util.LinkedList;
import java.util.Queue;

public class MyStack {
    Queue<Integer> queue1;
    private int size = 0;

    public MyStack() {
        queue1 = new LinkedList<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        queue1.add(x);
        size++;
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        if (size == 0) {
            System.out.println("stack is empty");
        }else {
            int ret = 0;
            for (int i = 0; i <size-1 ; i++) {
                ret = queue1.poll();
                queue1.add(ret);
            }
        }
        size--;
        return queue1.poll();
    }
    /** Get the top element. */
    public int top() {
        if (size == 0) {
            System.out.println("stack is empty");
            return 0;
        }else {
            int ret = 0;
            for (int i = 0; i <size-1 ; i++) {
                ret = queue1.poll();
                queue1.add(ret);
            }
            ret = queue1.poll();
            queue1.add(ret);
            return ret;
        }
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值