它是Double类型的双链接列表。我的其他方法不会与测试人员一起运行,因为他们说";这个"头";或";当前";为null,所以我假设add方法有问题,因为它是首先使用的。它正在投掷。任何帮助都将不胜感激!
{
private class ListNode
{
double data;
ListNode prev;
ListNode next;
public ListNode(Double aData, ListNode foreWards, ListNode backWards)
{
data = aData;
next = foreWards;
prev = backWards;
}
}
private ListNode head;
private ListNode current;
private ListNode previous;
private ListNode tail;
public DoubleDoubleLL()
{
head = current = previous = null;
}
public void add(Double aData)
{
ListNode newNode = new ListNode(aData, null, null);
if(head == null)
{
head = current = tail = newNode;
tail = current = newNode;
return;
}
else
{
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
tail.next = null;
ListNode temp = head;
temp = temp.next;
temp.next = newNode;
temp.prev = newNode;
}
}
}
首先,在第一条和最后一条记录的情况下,next或prev==为null是正常的。这就是我们指示列表开始和结束的方式。
至于您的添加方法,是的,它是错误的:(
看到这里的例子,我添加了一个带有一些打印输出的主方法,这样你就可以看到它是如何工作的。
public class DoubleLinkedList {
private ListNode head;
private ListNode tail;
private int size = 0;
private class ListNode {
double data;
ListNode prev;
ListNode next;
public ListNode(double data, ListNode prev, ListNode next) {
this.data = data;
this.prev = prev;
this.next = next;
}
public String toString(ListNode node) {
return node == null ? "NIL" : ""+node.hashCode();
}
public String toString() {
return String.format("ListNode [%d] [data: %f, next: %s, prev: %s]", this.hashCode(), this.data, this.toString(this.next),this.toString(this.prev));
}
}
public DoubleLinkedList() {
}
public void add(double data) {
this.size++;
ListNode node = new ListNode(data, this.tail, null);
if (this.tail != null) {
this.tail.next = node;
}
this.tail = node;
if (this.head == null) {
this.head = node;
}
}
public String toString(ListNode node) {
return node == null ? "NIL" : ""+node.hashCode();
}
public String toString() {
return String.format("DoubleLinkedList [%d] [size: %d, head: %s, tail: %s] (%s)", this.hashCode(), this.size, toString(this.head), toString(this.tail), this.printList());
}
private String printList() {
StringBuilder sb = new StringBuilder();
ListNode next = this.head;
while (next != null) {
sb.append("nt").append(next.toString()).append(",");
next = next.next;
}
return sb.toString();
}
public static void main(String[] args) {
DoubleLinkedList list = new DoubleLinkedList();
System.out.println(list.toString());
list.add(11);
System.out.println(list.toString());
list.add(12);
System.out.println(list.toString());
// adding two at once
list.add(13);
list.add(14);
System.out.println(list.toString());
}
}