数据结构-链队

文章目录

简介

链队就我们数据结构中通常说的队列,就是链式的队列,他也是线性表,FIFO,链式存储结构。队列还是很常见的,链队编写过程中还有一个小的细节点在下文中会做阐述,现在我们用 java 一起实现一遍吧!

Java 实现

逻辑思路

链队入队出队只要记住 FIFO 的规则就行了,都蛮好实现,但是有一个细节点不得不注意一下,我们平常的惯性思维是初始条件 head = tail,之后每有一个结点入队,我们就让当前的 tail 空间被结点占据,然后 tail 往后移到一个新空间处。逻辑上是没问题的,但是我们编程时候会非常麻烦,为什么呢?因为 tail 所在的空间还没有元素,它只有 next 指向,没法指向前一个结点,因此前一个结点的 next 无法指向插入的那个新结点!所以我们在写数据结构的过程中往往有个原则,那就是:

头结点为空,尾结点不为空!

依据这个原则我们怎么实现呢?最初条件是 head = tail,现在我们插入元素,我先让 tail 往后移动一个空间再往这个空间中存入结点,这样就能保证 tail 始终不是一个空的空间,而是表示尾部的结点,这样想让后续元素插入到队尾就很容易了

算法图解

链队

代码实现

// 结点
class Node {
    int data;
    Node next = null;
}

// 链队
public class LinkedQueue {
    // 队头
    private Node head;
    // 队尾
    private Node tail;
    
    // 初始化
    public LinkedQueue() {
        head = tail = null;
    }
    
    // 创建队列
    public void create(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            Node node = new Node();
            node.data = arr[i];
            node.next = null;
            tail.next = node;
            tail = node;
        }
    }
    
    // 返回队头
    public int getHead() {
        return head.next.data;
    }
    
    // 入队
    public void enqueue(Node n) {
        n.next = null;
        tail.next = n;
        tail = n;
    }
    
    // 出队
    public int dequeue() throws Exception {
        if (head == tail)
            throw new Exception("队空!");
        int e = head.next.data;
        head = head.next;
        return e;
    }
    
    // 求队长
    public int getLength() {
        int i = 0;
        for (head = h; h.next != tail; h = h.next,i++);
        return i+1;
    }
}
发布了197 篇原创文章 · 获赞 62 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/abcnull/article/details/104350176