首页 > 解决方案 > 在双向链表末尾插入节点

问题描述

我试图在双向链表的末尾插入一个节点,但是当我运行 add 方法时,代码永远不会完成运行。下面是代码:

public class DoublyLinkedList<T> {
    static class Node<T> {
        T data;
        Node<T> next;
        Node<T> previous;
        
        Node() {
            data = null;
            next = null;
            previous = null;
        }
        
        Node(T value) {
            data = value;
            next = null;
            previous = null;
        }
    }
    
    private Node<T> head;
    private int size;
        
    public DoublyLinkedList() {
        head = null;
    }
    
    public DoublyLinkedList(T value) {
        head = new Node<T>(value);
        size ++;
    }

    public void add(T value) {
        Node<T> append = new Node<T>(value);
        append.next = null;
        if(head == null) {
            append.previous = null;
            head = append;
            size ++;
            return;
        }
        Node current = head;
        while(current.next != null) {
            current = current.next;
        }
        current.next = append;
        append.previous = current;
        size ++;
    }

我很确定 current.next = append 这行是问题所在,但我不知道如何解决它。我究竟做错了什么?

标签: javadoubly-linked-list

解决方案


推荐阅读