這是我的全班同學,我在雙向鏈表中添加了第二個數字,然後我希望它可以在concole中打印,但它會顯示「[email protected]」 謝謝!爲什麼toString方法在這裏不起作用?
package datastructureproject;
public class DoublyLinkedList {
private Node head = new Node(0);
private Node tail = new Node(0);
private int length = 0;
public DoublyLinkedList() {
head.setPrev(null);
head.setNext(tail);
tail.setPrev(head);
tail.setNext(null);
}
public void add(int index, int value) throws IndexOutOfBoundsException {
Node cursor = get(index);
Node temp = new Node(value);
temp.setPrev(cursor);
temp.setNext(cursor.getNext());
cursor.getNext().setPrev(temp);
cursor.setNext(temp);
length++;
}
private Node get(int index) throws IndexOutOfBoundsException {
if (index < 0 || index > length) {
throw new IndexOutOfBoundsException();
} else {
Node cursor = head;
for (int i = 0; i < index; i++) {
cursor = cursor.getNext();
}
return cursor;
}
}
public long size() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("(head) - ");
Node temp = head;
while (temp.getNext() != tail) {
temp = temp.getNext();
result.append(temp.getValue() + " - ");
}
result.append("(tail)");
return result.toString();
}
public static void main(String[] args){
DoublyLinkedList list = new DoublyLinkedList();
list.add(0,2);
System.out.println(list.get(0).toString());
}
}
編輯:這也是我的Node類,謝謝!
class Node {
public int value;
public Node(){
}
public void setValue(int value) {
this.value = value;
}
public Node next;
public Node prev;
public Node(int value) {
this.value = value;
}
public Node(int value, Node prev, Node next) {
this.value = value;
setNext(next);
setPrev(prev);
}
public void setNext(Node next) {
this.next = next;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public Node getNext() {
return next;
}
public Node getPrev() {
return prev;
}
public int getValue() {
return value;
}
}
get方法能否請您正確格式化您的代碼,並提供節點的來源是什麼? – 2010-05-30 10:12:55
我已編輯我的文章! – user329820 2010-05-30 11:18:01