我正在进行计算机科学研究,我在将一个节点添加到双链表数据结构的末尾时遇到了一些困难。我知道新节点指向尾部,尾部指向它,因此我有:
public boolean add(E element)
{
// TODO: Implement this method
LLNode<E> newNode = new LLNode<E> (element);
if (element == null) {
throw new NullPointerException("Element can not store a null reference!");
} else {
newNode.next = tail;
newNode.prev = tail.prev;
tail.prev = newNode;
head.next = newNode;
}
size++;
return true;
}
我遇到的问题是尝试连接头节点(通过head.next到正确的节点)。
在我的默认构造函数中,我有head.next节点指向tail.prev。但是在add方法中,我无法确定head.next指向的位置,因为每次添加新节点时,head必须指向LinkedList数据结构中的第一个节点。这是默认构造函数:
public MyLinkedList() {
// TODO: Implement this method
size = 0;
/*create two empty nodes at the head and the tail of the linked list*/
head = new LLNode<E> (null);
tail = new LLNode<E> (null);
head.next = tail;
tail.prev = head;
head.prev = null; //Head is a sentinel node with no node prior to it
tail.next = null; //tail is a sentinel node with no node after it
}
请指出我(没有双关语)指向正确的方向。谢谢!
答案 0 :(得分:3)
在纸上画出你必须做的事情。
E.g。如果你列出当前有两个元素(A和B),你的链将是:
HEAD <-> A <-> B <-> TAIL
要添加新元素(C),最终结果应为:
HEAD <-> A <-> B <-> C <-> TAIL
表示以下更新:
C.prev = B
或更确切地说:C.prev = TAIL.prev
B.next = C
或更确切地说:TAIL.prev.next = C
C.next = TAIL
TAIL.prev = C
正如您所看到的,HEAD 不参与其中,因此您的第head.next = newNode
行是错误的。
答案 1 :(得分:1)
这应该有用。
public boolean add(E element)
{
LLNode<E> newNode = new LLNode<E> (element);
if (element == null) {
throw new NullPointerException("Element can not store a null reference!");
} else {
newNode.next = tail; // set new.next to tail
newNode.prev = tail.prev; // set new.prev to prior last
tail.prev.next = newNode; // set prior last.next to new last
tail.prev = newNode; // set tail.prev to new last
size++;
}
return true;
}
我不确定在add函数中是否需要检查null元素,尽管在其他地方可能需要进行null检查。
答案 2 :(得分:-1)
我认为您需要重新考虑如何处理链表... 你从一个链表开始像这样:
head.next = tail
head.prev = null
tail.next = null
tail.prev = head
当你在列表的末尾添加一些东西时,让我们在中间调用它,你希望你的列表看起来像这样:
head.next = mid (set by using tail.prev.next = mid)
head.prev = null
mid.next = tail (the new node is the end of the list)
mid.prev = head (previous tail.prev)
tail.next = null
tail.prev = mid (setting the new node to be the new end of the list)
所以你的错误在于,当你添加一个节点时,你不应该像你一样明确地使用头节点。所有操作都应该按照列表的尾部进行。我把它留给你把它变成代码。