【算法总结】【队列均LinkedList】栈和队列、双端队列的使用及案例
1、栈
初始化:Stack<E> stack = new Stack<>();
出栈:stack.pop() 或 stack.remove(stack.size() - 1)
入栈:stack.push(2) 或 stack.add(1)
栈顶:stack.peek()
2、队列
初始化:Queue<E> queue = new LinkedList<>();
入队:queue.offer(2) 或 queue.add(3)
出队:queue.poll() 或 queue.remove()
查看队头元素:queue.peek()
3、双端队列
初始化:
//Deque<Integer> deque = new ArrayDeque<>();
Deque<Integer> deque1 = new LinkedList<>();
入队:
deque1.addFirst(1);
deque1.addLast(2);
deque1.offerFirst(3);
deque1.offerLast(4);
出队:
deque1.removeFirst()
deque1.removeLast()
deque1.pollFirst()
deque1.pollLast()
查看队头元素:
deque1.peekFirst()
deque1.peekLast()
4、测试
public static void main(String[] args) { //System.out.println(isValid("([])")); //testQueue(); testStack(); } public static void testDeque() { //双端队列 Deque<Integer> deque = new ArrayDeque<>(); Deque<Integer> deque1 = new LinkedList<>(); //入队 deque1.addFirst(1); deque1.addLast(2); deque1.offerFirst(3); deque1.offerLast(4); System.out.println(deque1.peekFirst()); System.out.println(deque1.peekLast()); //出队 System.out.println(deque1.removeFirst()); System.out.println(deque1.removeLast()); System.out.println(deque1.pollFirst()); System.out.println(deque1.pollLast()); } public static void testQueue() { Queue<Integer> queue = new LinkedList<>(); queue.offer(1); queue.offer(2); queue.add(3); System.out.println(queue.peek()); System.out.println(queue.poll()); System.out.println(queue.peek()); System.out.println(queue.remove()); System.out.println(queue.peek()); } public static void testStack() { Stack<Integer> stack = new Stack<>(); stack.add(1); stack.push(2); stack.push(3); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.peek()); System.out.println(stack.remove(stack.size() - 1)); System.out.println(stack.peek()); }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15845958.html