Java-队列、栈

队列、栈

队列

java.util.Queue接口 队列

  • 队列是经典的数据结构之一,可以保存一组元素,但是存取元素必须遵循先进先出的原则
  • Queue接口继承自Collection

方法

  1. offer入队操作,元素会添加到队列末尾
Queue<String> queue = new LinkedList<>();
queue.offer("onr");
queue.offer("shghgs");
queue.offer("hssh");
queue.offer("isis");
System.out.println(queue);

输出结果: [onr, shghgs, hssh, isis]

  1. 出队操作,获取队首元素并将其从队列中删除
queue.offer("大家好");
queue.offer("我是");
queue.offer("人间人爱");
queue.offer("花见花开的");
queue.offer("carry");
System.out.println(queue);
String str = queue.poll();
System.out.println("删除元素:" + str);
System.out.println(queue);

输出结果:
[大家好, 我是, 人间人爱, 花见花开的, carry]
删除元素:大家好
[我是, 人间人爱, 花见花开的, carry]

  1. peak是引用队首元素,获取队首元素,不会将队首元素从队列中删除,队首元素仍然在队列中
str = queue.peek();
System.out.println(str);
System.out.println(queue);
//使用新循环遍历(迭代器)队列,元素不受影响
for(String s : queue) {
System.out.println(s);
}
System.out.println(queue);
  1. 使用poll方法遍历队列
while(queue.size() > 0) {
str = queue.poll();
System.out.println(str);
}
System.out.println(queue);

双端队列

java.util.Deque接口,双端队列
Deque继承自Queue,双端队列的特点是队列两端都可以做出入队的操作

public class DequeDemo {
	public static void main(String[] args) {
		Deque<String> deque = new LinkedList<>() ;
		deque.offer("one") ;
		deque.offer("two") ;
		deque.offer("three") ;
		System.out.println(deque) ;
		//从队首方向入队
		deque.offerFirst("four");
		System.out.println(deque);
		//从队尾方向入队
		deque.offerLast("five");
		System.out.println(deque);
		//从队首方向出队
		deque.pollFirst();
		System.out.println(deque);
		//从队尾方向出队
		deque.pollLast();
		System.out.println(deque);
		
	}
}

输出结果:
[one, two, three]
[four, one, two, three]
[four, one, two, three, five]
[one, two, three, five]
[one, two, three]

概述

栈是经典的数据结构之一,可以保存一组元素,但是存取元素必须遵循先进后出的原则
一般使用栈来实现“后退”这样的功能

方法

  1. void push(E e)入栈
Deque<String> stack = new LinkedList<>();
		stack.push("a");
		stack.push("b");                                                                                                                                                                                                                                                                                                                                                                                                                                                               
		stack.push("c");
		System.out.println(stack);

输出结果:[c,b,a]

  1. E pop()出栈
String str = stack.peek();
System.out.println(str);
String str1 = stack.pop();
System.out.println(str1);
System.out.println(stack);

输出结果:
[c, b, a]
c
c
[b, a]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值