Common methods of confusing stacks, one-way queues, and two-way queues

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 stack
      • pop: Get and delete the top element of the stack
      • peek: Get but not delete the top element of the stack

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 queue
      • poll: Get and delete the head element
      • peek: Get but not delete the head element

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

Guess you like

Origin blog.csdn.net/qq_42397330/article/details/122740323