DLList:我的函数没有产生预期的输出

时间:2017-02-09 02:45:16

标签: java

对于数据结构课程,我基于此DLList Tutorial创建了一个DLList程序。我创建了两个函数displayWithForLoop()display()。我被期望他们产生相同的输出,但他们没有。那是为什么?

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()不同?

1 个答案:

答案 0 :(得分:1)

很难说为什么输出方式与您提供的方式不同,但您的displayWithForLoop方法似乎跳过了打印列表的头部。 您可以在for循环中交换两个调用的顺序:

public displayWithForLoop() {
    Node pointer = head;
    for (int i = 0; i < size - 1; i++) {
        System.out.println(pointer.element);
        pointer = pointer.next;
    }
}