【发布时间】:2021-04-16 20:28:05
【问题描述】:
所以我一直在研究双向链表,我想在列表的开头插入一个值。 我们应该有两种情况:
- 空列表的情况。
- 非空列表的情况。
我认为我所做的是正确的,但我仍然对结果有疑问。
public class DoublyLinkedList {
class Element{
int data ;
Element next = null; //reference the next element
Element previous = null; //reference to the previous element
Element(int value){
data = value;
next = null;
previous = null;
}
}
private Element head = null; //reference to the head of the list
private Element rear = null; //reference to the rear of the list
private int length = 0;
public static final int NOT_FOUND = -1;
//getter return the number of items in the list
public int getLength() {
return length;
}
public DoublyLinkedList() {
this.head = null;
this.rear = null;
this.length = 0;
}
public DoublyLinkedList(DoublyLinkedList dList) {
this();
if(dList.isEmpty())
return;
Element cur = dList.head;
Element tmp = new Element(cur.data);
head = rear = tmp;
cur = cur.next;
length++;
while(cur != null) {
tmp = new Element(cur.data);
rear.next = tmp;
tmp.previous = rear;
rear = tmp;
cur = cur.next;
length++;
}
}
public boolean isEmpty() {
return length == 0;
}
public String toString() {
Element cur = this.head;
String str;
if (isEmpty())
str = "The list is empty";
else {
str = "|";
while (cur != null) {
str += cur.data + "|";
cur = cur.next;
}
System.out.println();
}
return str;
}
public void insertAtHead(int value) {
Element tmp = new Element(value);
// case on an empty list
if(this.isEmpty()) {
head = rear = tmp;
head.previous = null;
rear.next = null;
}else {
//case of a non-empty list
tmp.next = head;
head.previous = tmp;
tmp.previous = null;
head = tmp;
this.length++;
}
}
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.insertAtHead(1);
list.insertAtHead(2);
list.insertAtHead(3);
list.insertAtHead(4);
list.insertAtHead(5);
System.out.println(list);
list.insertBetween2Nodes(3);
System.out.println(list);
}
}
它总是给我这个结果:
列表为空。
【问题讨论】:
-
阅读this article 了解调试代码的技巧。
-
Java 还是 Javascript?这就是问题...
-
我想我看到了错误,但为了您自己的教育,我认为您应该尝试自己找到它。这很简单。从上面的链接,从“橡皮鸭”解决方案开始。如果您自己浏览代码,很容易找到。如果仍然找不到,请尝试编写更小的测试用例。您目前正尝试一次性插入五个元素。尝试仅插入一个元素并在调试器中查看结果。注意前置条件和后置条件的概念。您缺少重要的一项。
-
方法
isEmpty()在哪里定义的? -
你为什么在
toString()中有一个println()电话?
标签: java class adt doubly-linked-list