1.实现队列
【详细图解】学习队列,看这一篇就够了! - 掘金 (juejin.cn)
队列的特点是节点的排队次序和出队次序按入队时间先后确定,即先入队者先出队,后入队者后出队,即我们常说的FIFO(first in first out)先进先出。队列实现方式也有两种形式,基于数组和基于链表。 对于基于链表,因为链表的长度是随时都可以变的,实现起来比较简单。如果是基于数组的,会有点麻烦,我们将其放在黄金挑战里再看,这里只看一下基于链表实现的方法。
基于链表实现队列还是比较好处理的,只要在尾部后插入元素,在front删除元素就行了。
思路:
定义三个变量,front 和 read 保存队列头和队列尾的数据,分别是 Node 类型,size 用来记录队列长度。
新增元素:因为这是一个链表,要满足
先进先出(FIFO)
,所以要将新增的元素保存到链表尾部。先需要一个变量通过循环到链表的尾部,然后使尾部 连接这个新节点就可以了,并且使read
记录尾部,长度size++
。删除元素:把链表头删除了就行。
代码:
package com.yugutou.charpter5_queue_map.level1;
public class LinkedQueue {
public Node front; // 记录第一个
public Node rear; // 记录最后一个
public int size; // 长度
// 初始化队列
public LinkedQueue() {
this.front = new Node(0);
this.rear = new Node(0);
}
/**
* 定义静态内部内链表
*/
static class Node{
public int val;
public Node next;
public Node(int val) {
this.val = val;
next = null;
}
}
public static void main(String[] args) {
LinkedQueue linkedQueue = new LinkedQueue();
linkedQueue.push(1);
linkedQueue.push(2);
linkedQueue.push(3);
linkedQueue.push(4);
linkedQueue.push(5);
linkedQueue.printLinkQueue();
}
/**
* 新增节点
* @param val
*/
public void push(int val) {
// 新节点
Node newNode = new Node(val);
// 保存在链表末尾
Node temp = front;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
// 记录末尾
rear = newNode;
size++;
}
/**
* 出队列
* @return
*/
public int pull() {
// 判空
if (front.next == null) {
throw new RuntimeException("队列为空!");
}
Node outNode = front.next;
front.next = front.next.next;
size--;
return outNode.val;
}
public void printLinkQueue() {
Node temp = front.next;
while (temp != null) {
System.out.print(temp.val + "->" + "\t");
temp = temp.next;
}
System.out.println("null");
}
}