我试图在双链表的末尾插入一个节点,但是当我运行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这行是问题所在,但我不确定如何修复它。我做错什么了?
暂无答案!
目前还没有任何答案,快来回答吧!