Java数据结构--栈和队列

一、 栈

「栈 stack」是一种遵循先入后出的逻辑的线性数据结构。

我们可以将栈类比为桌面上的一摞盘子,如果想取出底部的盘子,则需要先将上面的盘子依次移走。我们将盘子替换为各种类型的元素(如整数、字符、对象等),就得到了栈这种数据结构。

如图所示,我们把堆叠元素的顶部称为“栈顶”,底部称为“栈底”。将把元素添加到栈顶的操作叫作“入栈”,删除栈顶元素的操作叫作“出栈”。
栈

1.1 栈常用操作

方法描述时间复杂度
push()元素入栈(添加至栈顶)O(1)
pop()栈顶元素出栈O(1)
peek()访问栈顶元素O(1)

1.2 栈的实现

栈遵循先入后出的原则,因此我们只能在栈顶添加或删除元素。然而,数组和链表都可以在任意位置添加和删除元素,因此栈可以视为一种受限制的数组或链表。

1.2.1 基于链表的实现

  • 元素入栈
    入栈操作
  • 元素出栈
    出栈操作
linkedlist_stack.java

	// 链表实现
	public class ListNode {
	    /*链表节点类*/
	    public int val; //节点值
	    public ListNode next; // 指向下一节点的引用
	    public ListNode(int x) { // 构造函数
	        val = x;
   		}
	}

	// 基于链表实现栈
	public static class LinkedListStack {
        private ListNode stackPeek; // 将头节点作为栈顶
        private int stkSize = 0; // 栈的长度

        public LinkedListStack() {
            stackPeek = null;
        }

        /*获取栈的长度*/
        public int size() {
            return stkSize;
        }

        /*判断栈是否为空*/
        public boolean isEmpty() {
            return size() == 0;
        }

        /*入栈*/
        public void push(int num) {
            ListNode node = new ListNode(num);
            node.next = stackPeek;
            stackPeek = node;
            stkSize++;
        }

        /*出栈*/
        public  int pop() {
            int num = peek();
            stackPeek = stackPeek.next;
            stkSize--;
            return num;
        }

        /*访问栈顶元素*/
        public int peek() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return stackPeek.val;
        }

        /*将List转化为Array并返回*/
        public int[] toArray() {
            ListNode node = stackPeek;
            int[] res = new int[size()];
            for(int i = res.length - 1;i >= 0; i--) {
                res[i] = node.val;
                node = node.next;
                System.out.println("索引为" + i + ":" + res[i]);
            }
            return res;
        }
    }

    public static void main(String[] args) {
    	// 测试类
        LinkedListStack stack = new LinkedListStack();
        // 初始化栈
        stack.push(1);
        stack.push(3);
        stack.push(2);
        stack.push(5);
        stack.push(4);

        // 访问栈顶
        System.out.println(stack.peek());

        // 输出整个栈
        stack.toArray();
    }

1.2.2 基于数组的实现

使用数组实现栈时,我们可以将数组的尾部作为栈顶。如图所示,入栈与出栈操作分别对应在数组尾部添加元素与删除元素,时间复杂度都为O(1)。

  • 元素入栈
    元素入栈

  • 元素出栈
    元素出栈

array_stack.java

	// 基于数组实现的栈
	public static class ArrayStack {
        private ArrayList<Integer> stack;

        public ArrayStack() {
            // 初始化列表(动态数组)
            stack = new ArrayList<>();
        }

        /* 获取栈的长度 */
        public int size() {
            return stack.size();
        }

        /* 判断栈是否为空 */
        public boolean isEmpty() {
            return size() == 0;
        }

        /* 入栈 */
        public void push(int num) {
            stack.add(num);
        }

        /* 出栈 */
        public int pop() {
            if (isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return stack.remove(size() - 1);
        }

        /* 访问栈顶元素 */
        public int peek() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return stack.get(size() - 1);
        }

        /* 将List转化为Array并返回 */
        public Object[] toArray() {
            return stack.toArray();
        }
    }

    public static void main(String[] args) {
    	// 测试类
        ArrayStack stack = new ArrayStack();
        stack.push(1);
        stack.push(3);
        stack.push(2);
        stack.push(5);
        stack.push(4);

        System.out.println(stack.peek());
    }

二、 队列

「队列 queue」是一种遵循先入先出规则的线性数据结构。顾名思义,队列模拟了排队现象,即新来的人不断加入队列尾部,而位于队列头部的人逐个离开。

如图所示,我们将队列头部称为“队首”,尾部称为“队尾”,将把元素加入队尾的操作称为“入队”,删除队首元素的操作称为“出队”。
队列

2.1 队列常用操作

方法名描述时间复杂度
push()元素入队,即元素添加至队尾O(1)
pop()队首元素出队O(1)
peek()访问队首元素O(1)

2.2 队列实现

为了实现队列,我们需要一种数据结构,可以在一端添加元素,并在另一端删除元素。链表和数组都符合要求。

2.2.1 基于链表的实现

我们可以将链表的“头节点”和“尾节点”分别视为“队首”和“队尾”,规定队尾仅可添加节点,队首仅可删除节点。

  • 元素入队
    元素入队
  • 元素出队
    元素出队
linkedlist_queue.java

	// 链表实现
	public class ListNode {
	    /*链表节点类*/
	    public int val; //节点值
	    public ListNode next; // 指向下一节点的引用
	    public ListNode(int x) { // 构造函数
	        val = x;
	    }
	}

	// 基于链表实现的队列
    public static class LinkedListQueue {
        private ListNode front, rear; // 头节点 front, 尾节点 rear
        private int queSize = 0;

        public LinkedListQueue() {
            front = null;
            rear = null;
        }

        /* 获取队列的长度 */
        public int size() {
            return queSize;
        }

        /* 判断队列是否为空 */
        public boolean isEmpty() {
            return size() == 0;
        }

        /* 入队 */
        public void  push(int num) {
            // 尾节点后添加 num
            ListNode node = new ListNode(num);
            // 如果队列为空,则令头、尾节点都指向该节点
            if(front == null) {
                front = node;
                rear = node;
            }
            // 如果队列不为空,则该节点添加到尾节点后
            else {
                rear.next = node;
                rear = node;
            }
            queSize++;
        }

        /* 出队 */
        public int pop() {
            int num = peek();
            // 删除头节点
            front = front.next;
            queSize--;
            return num;
        }

        /* 访问队首元素 */
        public int peek() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return front.val;
        }

        /* 将链表转化为Array并返回 */
        public int[] toArray() {
            ListNode node = front;
            int[] res = new int[size()];
            for(int i = 0; i < res.length; i++) {
                res[i] = node.val;
                node = node.next;
                System.out.println("第" + (i + 1) + "个队列元素为" + res[i]);
            }
            return res;
        }
    }

    public static void main(String[] args) {
   		 // 测试类
        LinkedListQueue queue = new LinkedListQueue();
        queue.push(1);
        queue.push(3);
        queue.push(2);
        queue.push(5);
        queue.push(4);
        System.out.println("访问队首元素" + queue.peek());
        queue.toArray();
    }

2.2.1 基于数组的实现

在数组中删除首元素的时间复杂度为O(n),这会导致出队操作效率较低。然而,我们可以采用以下巧妙方法来避免这个问题。

我们可以使用一个变量 front 指向队首元素的索引,并维护一个变量 size 用于记录队列长度。定义 rear = front + size ,这个公式计算出的 rear 指向队尾元素之后的下一个位置。

基于此设计,数组中包含元素的有效区间为 [front, rear - 1],各种操作的实现方法如图所示。

  • 入队操作:将输入元素赋值给 rear 索引处,并将 size 增加 1 。
  • 出队操作:只需将 front 增加 1 ,并将 size 减少 1 。

可以看到,入队和出队操作都只需进行一次操作,时间复杂度均为O(1)。

  • 元素入队
    元素入队

  • 元素出队
    元素出队

你可能会发现一个问题:在不断进行入队和出队的过程中,front 和 rear 都在向右移动,当它们到达数组尾部时就无法继续移动了。为了解决此问题,我们可以将数组视为首尾相接的“环形数组”。

对于环形数组,我们需要让 front 或 rear 在越过数组尾部时,直接回到数组头部继续遍历。这种周期性规律可以通过“取余操作”来实现,代码如下所示:

array_queue.java

	// 基于环形数组实现的队列
	public static class ArrayQueue {
        private int[] nums; // 用于存储队列元素的数组
        private int front; // 队首指针,指向队首元素
        private int queSize; // 队列长度

        public ArrayQueue(int capacity) {
            nums = new int[capacity];
            front = queSize = 0;
        }

        /* 获取队列的容量 */
        public int capacity() {
            return nums.length;
        }

        /* 获取队列的长度 */
        public int size() {
            return queSize;
        }

        /* 判断队列是否为空 */
        public boolean isEmpty() {
            return queSize == 0;

        }

        /* 入队 */
        public void push(int num) {
            if(queSize == capacity()) {
                System.out.println("队列已满");
                return;
            }
            // 计算尾指针, 指向队尾索引 + 1
            // 通过取余操作,  实现rear越过数组尾部后回到头部
            int rear = (front + queSize) % capacity();
            // 将 num 添加至队尾
            nums[rear] = num;
            queSize++;
        }

        /* 出队 */
        public int pop() {
            int num = peek();
            // 队首指针向后移动一位, 若越过尾部则返回到数组头部
            front = (front + 1) % capacity();
            queSize--;
            return  num;
        }

        /* 访问队首元素 */
        public int peek() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return nums[front];
        }

        /* 返回数组 */
        public int[] toArray() {
            // 仅转换有效长度范围内的列表元素
            int[] res = new int[queSize];
            for(int i = 0, j = front; i < queSize; i++, j++) {
                res[i] = nums[j % capacity()];
                System.out.println("第" + i + "个队列元素为:" + res[i]);
            }
            return res;
        }
    }

    public static void main(String[] args) {
    	// 测试类
        ArrayQueue queue = new ArrayQueue(5);
        queue.push(1);
        queue.push(3);
        queue.push(2);
        queue.push(5);
        queue.push(4);
        
        queue.toArray();
    }
}

三、 双向队列

在队列中,我们仅能删除头部元素或在尾部添加元素。如图所示,「双向队列 double-ended queue」提供了更高的灵活性,允许在头部和尾部执行元素的添加或删除操作。
双向队列

3.1 队列常用操作

方法名描述时间复杂度
pushFirst()将元素添加至队首O(1)
pushLast()将元素添加至队尾O(1)
popFirst()删除队首元素O(1)
popLast()删除队尾元素O(1)
peekFirst()访问队首元素O(1)
peekLast()访问队尾元素O(1)

3.2 双向队列实现

双向队列的实现与队列类似,可以选择链表或数组作为底层数据结构。

3.2.1 基于双向链表的实现

linkedlist_deque.java

	// 双向链表节点
	public static class ListNode {
        int val; //节点值
        ListNode next; // 后继节点引用
        ListNode prev; // 前驱节点引用

        ListNode(int val) {
            this.val = val;
            prev = next = null;
        }
    }
   
	// 基于双向链表实现的双向队列   
	public static class LinkedListDeque {
        private ListNode front, rear; // 头节点 front  尾节点 rear
        private int queSize = 0; // 双向队列的长度

        public LinkedListDeque() {
            front = rear = null;
        }

        /* 获取双向队列的长度 */
        public int size() {
            return queSize;
        }

        /* 判断双向队列是否为空 */
        public boolean isEmpty() {
            return size() == 0;
        }

        /* 入队操作 */
        private void push(int num, boolean isFront) {
            ListNode node = new ListNode(num);
            // 若链表为空,则令front 和 rear 都指向 node
            if (isEmpty()) {
                front = rear = node;
            }
            // 队首入队操作
            else if (isFront) {
                // 将 node 添加至链表头部
                front.prev = node;
                node.next = front;
                front = node;
            }
            // 队尾入队操作
            else {
                // 将 node 添加至链表尾部
                rear.next = node;
                node.prev = rear;
                rear = node;
            }
            queSize++; // 更新队列长度
        }

        /* 队首入队 */
        public void pushFirst(int num) {
            push(num, true);
        }

        /* 队尾入队 */
        public void pushLast(int num) {
            push(num, false);
        }

        /* 出队操作 */
        private int pop(boolean isFront) {
            if (isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            int val;
            // 队首出队操作
            if (isFront) {
                val = front.val; // 暂存头节点值
                // 删除头节点
                ListNode fNext = front.next;
                if (fNext != null) {
                    fNext.prev = null;
                    front.next = null;
                }
                front = fNext; // 更新头节点
            }
            // 队尾出队操作
            else {
                val = rear.val; // 暂存尾节点值
                // 删除尾节点
                ListNode rPrev = rear.prev;
                if (rPrev != null) {
                    rPrev.next = null;
                    rear.prev = null;
                }
                rear = rPrev; // 更新尾节点
            }
            queSize--; // 更新队列长度
            return val;
        }

        /* 队首出队 */
        public int popFirst() {
            return pop(true);
        }

        /* 队尾出队 */
        public int popLast() {
            return pop(false);
        }

        /* 访问队首元素 */
        public int peekFrist() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return front.val;
        }

        /* 访问队尾元素 */
        public int peekLast() {
            if(isEmpty()) {
                throw new IndexOutOfBoundsException();
            }
            return rear.val;
        }

        /* 返回数组用于打印 */
        public int[] toArray() {
            ListNode node= front;
            int[] res = new int[size()];
            for(int i = 0; i < res.length; i++) {
                res[i] = node.val;
                System.out.println("队列第" + i + "个元素为:" + res[i]);
                node = node.next;
            }
            return res;
        }
    }

	public static void main(String[] args) {
    	// 测试类
        LinkedListDeque listDeque = new LinkedListDeque();
        listDeque.pushFirst(1);
        listDeque.pushFirst(3);
        listDeque.pushFirst(5);
        listDeque.pushFirst(7);
        listDeque.pushFirst(9);
        listDeque.pushLast(4);

        listDeque.popFirst();

        listDeque.toArray();
    }

3.2.2 基于环形数组的实现

array_deque.java

	/* 基于环形数组实现的双向队列 */
    public static class ArrayDeque {
        private int[] nums; // 用于存储双向队列元素的数组
        private int front; // 队首指针,指向队首元素
        private int queSize; // 双向队列长度

        /* 构造方法 */
        public ArrayDeque(int capacity) {
            this.nums = new int[capacity];
            front = queSize = 0;
        }

        /* 获取双向队列的容量 */
        public int capacity() {
            return nums.length;
        }

        /* 获取双向队列的长度 */
        public int size() {
            return queSize;
        }

        /* 判断双向队列是否为空 */
        public boolean isEmpty() {
            return queSize == 0;
        }

        /* 计算环形数组索引 */
        private int index(int i) {
            // 通过取余操作实现数组首尾相连
            // 当 i 越过数组尾部后,回到头部
            // 当 i 越过数组头部后,回到尾部
            return (i + capacity()) % capacity();
        }

        /* 队首入队 */
        public void pushFirst(int num) {
            if (queSize == capacity()) {
                System.out.println("双向队列已满");
                return;
            }
            // 队首指针向左移动一位
            // 通过取余操作,实现 front 越过数组头部后回到尾部
            front = index(front - 1);
            // 将 num 添加至队首
            nums[front] = num;
            queSize++;
        }

        /* 队尾入队 */
        public void pushLast(int num) {
            if (queSize == capacity()) {
                System.out.println("双向队列已满");
                return;
            }
            // 计算尾指针,指向队尾索引 + 1
            int rear = index(front + queSize);
            // 将 num 添加至队尾
            nums[rear] = num;
            queSize++;
        }

        /* 队首出队 */
        public int popFirst() {
            int num = peekFirst();
            // 队首指针向后移动一位
            front = index(front + 1);
            queSize--;
            return num;
        }

        /* 队尾出队 */
        public int popLast() {
            int num = peekLast();
            queSize--;
            return num;
        }

        /* 访问队首元素 */
        public int peekFirst() {
            if (isEmpty())
                throw new IndexOutOfBoundsException();
            return nums[front];
        }

        /* 访问队尾元素 */
        public int peekLast() {
            if (isEmpty())
                throw new IndexOutOfBoundsException();
            // 计算尾元素索引
            int last = index(front + queSize - 1);
            return nums[last];
        }

        /* 返回数组用于打印 */
        public int[] toArray() {
            // 仅转换有效长度范围内的列表元素
            int[] res = new int[queSize];
            for (int i = 0, j = front; i < queSize; i++, j++) {
                res[i] = nums[index(j)];
                System.out.println("队列第" + i + "个元素为:" + res[i]);
            }
            return res;
        }
    }

    public static void main(String[] args) {
    	// 测试类
        ArrayDeque arrayDeque = new ArrayDeque(10);
        arrayDeque.pushFirst(4);
        arrayDeque.pushFirst(2);
        arrayDeque.pushFirst(5);
        arrayDeque.pushLast(1);
        arrayDeque.pushLast(7);

        arrayDeque.toArray();
    }
  • 26
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值