【Java】栈和队列

本文介绍了队列和栈这两种基本数据结构的操作方法,包括队列的添加、删除及遍历,栈的压栈、出栈及遍历等,并通过Java代码实现展示了这些操作的具体过程。

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

public class QueueAndStack {
	private static final long LEVEL = 20150701;//码讲版本
	/**
	 * 队列的基本操作
	 */
	public void testQueue() {
		Queue<String> queue = new LinkedList<String>();
		System.out.println("向队尾添加元素:"+queue.offer("one"));
		queue.offer("two");
		queue.offer("three");
		queue.offer("four");
		System.out.println("全部队列:" + queue);
		System.out.println("出队操作:" + queue.poll());
		System.out.println("取出后全部队列:" + queue);
		System.out.println("查询队尾元素,不出队:"+queue.peek());
		System.out.println("查询后全部队列:" + queue);
		System.out.println("当前队列元素个数:"+queue.size());
		//队列的遍历 while方式并做出队操作
		while(queue.size()>0){
			System.out.println("遍历:"+queue.poll());
		}
		System.out.println("While遍历后队列:"+queue);
		//迭代器遍历,不会做出队操作
		System.out.println("向队尾添加元素:"+queue.offer("one"));
		queue.offer("two");
		queue.offer("three");
		queue.offer("four");
		for(String q:queue){
			System.out.println("遍历:"+q);
		}
		System.out.println("迭代遍历后队列:"+queue);
	}
	/**
	 * 栈的基本操作
	 */
	@Test
	public void testStack(){
		Deque<String> stack = new LinkedList<String>();
		stack.push("one");
		stack.push("two");
		stack.push("three");
		stack.push("four");
		System.out.println("查看栈顶元素:"+stack.peek());
		System.out.println("出栈:"+stack.pop());
		System.out.println("查看栈顶元素:"+stack.peek());
		System.out.println("栈大小:"+stack.size());
		//迭代遍历
		for(String q:stack){
			System.out.println("遍历:"+q);
		}
		System.out.println("迭代遍历后队列:"+stack);
		//出栈遍历
		while(stack.size()>0){
			System.out.println("出栈遍历:"+stack.pop());
		}
		System.out.println("栈大小:"+stack.size());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xerophyte000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值