Java-队列、栈

    技术2022-07-10  159

    队列、栈

    队列、栈队列方法 双端队列栈概述方法

    队列、栈

    队列

    java.util.Queue接口 队列

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

    方法

    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]

    出队操作,获取队首元素并将其从队列中删除 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]

    peak是引用队首元素,获取队首元素,不会将队首元素从队列中删除,队首元素仍然在队列中 str = queue.peek(); System.out.println(str); System.out.println(queue); //使用新循环遍历(迭代器)队列,元素不受影响 for(String s : queue) { System.out.println(s); } System.out.println(queue); 使用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]

    概述

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

    方法

    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]

    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]

    Processed: 0.009, SQL: 9