Java 中的Stack和Queue

121 阅读1分钟

Stack

java.util.stack继承了Vector的子类,它提供了一系列的操作实现使用vector做栈的相关操作。

  • 构造方法:

    • stack(): 无参构造,初始栈为空
  • 主要方法:

    • boolean isEmpty(): 判空
    • E peek(): 获取栈顶元素
    • E pop(): 出栈
    • E push(E item): 入栈
    • int search(Object obj): 返回指定元素在栈中的位置,位置表示为到栈顶的距离
import java.util.Stack;

public class StackMain {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);

        System.out.println(stack); // [1, 2, 3, 4, 5]

        System.out.println(stack.peek()); // 5

        System.out.println(stack.pop()); // 5
        System.out.println(stack);  // [1, 2, 3, 4]
        System.out.println(stack.isEmpty()); // false

        System.out.println(stack.search(2));  // 3
    }
}

Queue

java.util.Queue是一个泛型接口,继承了Collection和Iterable两个接口,因此使用时需使用它的实现类。接口中的方法主要有:

  • boolean add(E e): 增加一个元索 ,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
  • E element(): 返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
  • boolean offer(E e): 将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则返回false;
  • E peek(): 返回队列头部的元素,如果队列为空,则返回null
  • E poll():移除并返回队列头部的元素 如果队列为空,则返回null
  • E remove():移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
import java.util.LinkedList;
import java.util.Queue;

public class QueueMain {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<Integer>();

        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(5);
        System.out.println(queue);  // [1, 2, 3, 4, 5]

        System.out.println(queue.peek()); // 1

        boolean flag = queue.offer(10);
        System.out.println(flag);  // true

        System.out.println(queue.peek()); // 1

        System.out.println(queue);  // [1, 2, 3, 4, 5, 10]
        System.out.println(queue.poll());  // 1
        System.out.println(queue);   //[2, 3, 4, 5, 10]

        System.out.println(queue.remove());  // 2
        System.out.println(queue);  // [3, 4, 5, 10]
    }