-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'列表的大小。非常感谢你的帮助,善良的先生。 –