1. Use of stack
- Example:
Deque<Integer> stack = new LinkedList<Integer>(); stack.push(1); stack.push(3); stack.push(2); System.out.println(stack.size()); // 3 System.out.println(stack.isEmpty()); // false stack.pop(); System.out.println(stack.peek()); // 3
- Summarize:
- Construction method:
Deque<Integer> stack = new LinkedList<Integer>();
- Member methods:
push
: Add elements to the top of the stackpop
: Get and delete the top element of the stackpeek
: Get but not delete the top element of the stack
- Construction method:
2. Use of queues
- Example:
Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(1); queue.offer(3); queue.offer(2); System.out.println(queue.size()); // 3 System.out.println(queue.isEmpty()); // false System.out.println(queue.peek()); // 1 queue.poll(); System.out.println(queue.peek()); // 3 ```
- Summarize:
- Construction method:
Queue<Integer> queue = new LinkedList<Integer>();
- Member methods:
offer
: Insert element to the end of the queuepoll
: Get and delete the head elementpeek
: Get but not delete the head element
- Construction method:
3. Use of two-way queue
- Construction method:
Deque<Integer> stack = new LinkedList<Integer>();
- Member methods: All the above member methods can be used, so we can just use the deque as a queue or stack
- Methods corresponding to queues
offer
-offerLast
poll
-pollFirst
peek
-peekFirst
- Methods corresponding to the stack
push
-offerFirst
pop
-pollFirst
peek
-peekFirst
- Methods corresponding to queues