-2
對於數據結構課程,我創建了一個基於此DLList Tutorial的DLList程序。我做了兩個功能displayWithForLoop()
和display()
。我希望他們能夠產出相同的產出,但他們沒有。這是爲什麼?DLList:我的函數不會產生預期的輸出
public class DLList<E> {
Node dummy, head, tail;
int size;
public DLList() {
size = 0;
}
class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public void pushNode(E item) {
Node newNode = newNode(item, head, dummy);
if(head != null) head.prev = newNode;
head = newNode;
if(tail == null) = newNode;
size++;
System.out.println("pushing: " + element);
}
public void display() {
System.out.println("iterating forward...");
Node pointer = head;
while (pointer != null) {
System.out.println(pointer.element);
pointer = pointer.next;
}
}
public displayWithForLoop() {
Node pointer = head;
for(int i = 0; i < size -1; i++) {
pointer = pointer.next;
System.out.println(pointer.element);
}
}
public static void main(String args[]) {
DLList<Integer> list = new DLList<Integer>();
list.pushNode(15);
list.pushNode(25);
list.pushNode(35);
list.displayWithForLoop();
System.out.println("***");
list.display();
}
}
我的輸出是: pushing: 15 pushing: 25 pushing: 35 3 25 15 *** iterating forward.. 35 25 15
爲什麼是list.displayWithForLoop()從list.display()不同的輸出?
您說得對。哦,我的天哪,我感到很尷尬。它是'3'而不是'35'的原因是因爲在我的原始代碼中,我使用函數getSize()來獲取在displayWithForLoop()之前的'3'列表的大小。非常感謝你的幫助,善良的先生。 –