文章目录

 

简介

单链表有个缺点,那就是我们只能顺着一个方向找到尾,不能反方向往回找,因此我们自然而然想到双向链表

Java 实现

逻辑思路

双链表比单向链表多了一个前去结点,所以比单链表要灵活一下,我们在插入结点或者删除结点时候需要考虑到四个连接,我们先考虑新结点的两个连接,然后我们在考虑新结点两边的两个结点的两个连接即可

算法图解

数据结构-双向链表_算法

代码实现

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

// 双向链表
public class DoubleLinkedList {
    // 头结点
    private Node head;
    
    // 初始化
    public DoubleLinkedList() {
        head = null;
    }
    
    // 头插法创建双向链表(倒序)
    public void createFromHead(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            Node node = new Node();
            node.data = arr[i];
            node.next = head.next;
            node.prior = head;
            node.next.prior = node;
            head.next = node;
        }
    }
    
    // 尾插法创建双向链表(正序)
    public void createFromTail(int[] arr) {
        Node h = head;
        for (int i = 0; i < arr.length; i++) {
            Node node = new Node();
            node.data = arr[i];
            node.prior = h;
            h.next = node;
            h = node;
        }
    }
    
    // 添加
    public void add(Node n) {
        Node h;
        for (h = head; h.next != null; h = h.next);
        h.next = n;
        n.prior = h;
    }
    
    // 查找
    public int search(int num) {
        int k = 0;
        for (Node h = head; h.next != null; k++,h = h.next);
        if (num < 1 || num > k)
            throw new Exception("数字超过范围!");
        Node h = head;
        for (int i = 1; i <= num; i++,h = h.next);
        return h.data;
    }
    
    // 插入
    public void insert(int num, Node n) {
        int k = 0;
        for (Node h = head; h.next != null; k++,h = h.next);
        if (num < 1 || num > k)
            throw new Exception("数字超过范围!");
        Node h = head;
        for (int i = 1; i < num; i++,h = h.next);
        n.next = h.next;
        n.prior = h;
        n.next.prior = n;
        h.next = n;
    }
    
    // 删除
    public int delete(int num) {
        int k = 0;
        for (Node h = head; h.next != null; k++,h = h.next);
        if (num < 1 || num > k)
            throw new Exception("数字超过范围!");
        Node h = head;
        for (int i = 1; i < num; i++,h = h.next);
        int e = h.next.data;
        h.next.next.prior = h;
        h.next = h.next.next;
        return e;
    }
}