链接列表,不正确添加值

时间:2013-04-04 23:35:46

标签: java

我正在进行我的任务,即实现LinkedList数据结构,我已完成所有代码,但它没有正常工作,我正在测试它的输入代码是“1,2,3 ,4,5“,但只输出”1“而不是所有值。

这是我的代码:

// Main Method Functions
private static LinkedList createLinkedList(int[] values) {
    LinkedList list;

    list = new LinkedList();
    for (int i = 0; i < values.length; i++) {
        list.add(values[i]);
    }
    return list;
}

private static void printList(LinkedList list) {
    Node currentNode = list.getHead();

    while(currentNode != null) {
        System.out.println(currentNode.getint());
        currentNode = currentNode.getNextNode();
    }
}

// LinkedList class functions
public void add(int value) {
    Node newNode = new Node(value);
    Node currentNode;

    if(head == null) {
        head = newNode;
    } else {
        currentNode = newNode;

        while(currentNode.getNextNode() != null) {
            currentNode = currentNode.getNextNode();
        }
        currentNode.setNextNode(newNode);
    }
    size++;
}

有谁可以指出我做错了什么?如果您需要添加任何其他功能,请告诉我们,谢谢。

编辑:显示要添加的值的函数:

private static void processLinkedList() {
    int[] values = new int[] {1,2,3,4,5};
    LinkedList list = createLinkedList(values);
    printList(list);
    System.out.println(list);
}

2 个答案:

答案 0 :(得分:1)

add()方法中,

currentNode = newNode;

应该可以改为

currentNode = head;

看看是否会让你前进。

答案 1 :(得分:1)

你可能应该更换
否则{
        currentNode = newNode;
通过
否则{
        currentNode = head;

相关问题