队列模拟栈

Java中的队列

import java.util.Queue;
import java.util.LinkedList;
 
public class QueueExample {
    public static void main(String[] args) {
        // 创建一个Queue对象
        Queue<String> queue = new LinkedList<>();
 
        // 添加元素到队列
        queue.add("Apple");
        queue.add("Banana");
        queue.add("Orange");
 
        // 获取队列头部元素
        String head = queue.peek();
        System.out.println("头部元素:" + head);
 
        // 遍历队列并输出元素
        System.out.println("队列元素:");
        for (String element : queue) {
            System.out.println(element);
        }
 
        // 移除队列头部元素
        String removedElement = queue.remove();
        System.out.println("移除的元素:" + removedElement);
 
        // 队列大小
        int size = queue.size();
        System.out.println("队列大小:" + size);
 
        // 判断队列是否为空
        boolean isEmpty = queue.isEmpty();
        System.out.println("队列是否为空:" + isEmpty);
    }
}

队列模拟栈

栈是后进先出的数据结构
队列是先进先出的数据结构

package 队列;

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

public class leetcode225 {
    public static void main(String[] args) {

    }

}
class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

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

    public void push(int x) {
        //队列插入元素
        queue2.offer(x);
        //如果不是空
        while (!queue1.isEmpty()){
            //删除并返回元素 1就是空了
            queue2.offer(queue1.poll());
        }
        //然后1=2
        //2又是空
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }

    public int pop() {
        return queue1.poll();
    }

    public int top() {
        return queue1.peek();
    }

    public boolean empty() {
        return queue1.isEmpty();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值