将数字插入链接列表并在java中进行排序

时间:2016-12-02 19:38:34

标签: java algorithm list sorting insertion

我对此代码中的我非常有信心。从逻辑上讲,它对我来说是有意义的,但由于某种原因,该程序拒绝超过某一点。我不应该使用专有类或哈希表来做到这一点。我的列表节点是一个基本的单链表。假设我首先有一个虚拟列表,0,我能够在列表中添加一个数字,但这就是全部。除了添加第一个数字之外,这种方法不起作用。

假设我的列表为0 - > 2.我试图加1。

public void insert(int newElement) {
    List marker = head;
    List temp = new List(newElement, null);

    if (head.next == null) {
        head.next = temp;
    } else {
        while (marker.next != null) {
            if (newElement < marker.next.value) {
                temp.next = marker.next;
                marker.next = temp;
                marker = marker.next;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

public void insert(int val) {
    Item item = new Item(val);

    // the case when there is no item (not counting the dummy head)
    if (head.getNext() == null) {
        head.setNext(item);
        item.setNext(null);
    } else {
        // if there is at least one item....
        Item cursor = head.getNext();
        Item prev = cursor;

        // simply keep looping the list until the new value is less than a value in list
        // if the new value is greater than all the values in the list...
        // then the do-while loop will break when null is reached...
        // at the end of the list
        do {
            if (val < cursor.getVal()) {
                // break and insert
                break;
            }
            prev = cursor;
            cursor = cursor.getNext();
        } while (cursor != null);

        // insert the item
        item.setNext(cursor);

        // the case when the new value is the smallest and is to be inserted at head
        if (val < head.getNext().getVal()) {
            head = item;
        } else prev.setNext(item);
    }
}

这是您的代码段:

if (newElement < marker.next.value) {
    temp.next = marker.next;
    marker.next = temp;
    marker = marker.next;
}

拿一支铅笔和一张纸,然后找出这段代码。你会看到它有什么问题。取look at this个答案,然后看附图。这就是你应该如何真正调试有关链表的问题。该图像并非特定于您的代码,但它应该让您了解如何处理此类问题。

答案 1 :(得分:0)

这似乎正在起作用,我目前正在测试它并取得了良好的效果。任何人都可以找到我错过的代码问题吗?

public void insert(int newElement) {
    List marker = head;
    List temp = new List(newElement, null);

    if (head.next == null) {
        head.next = temp;
    } else {
        for (marker = head; marker.next != null; marker = marker.next) {
            if (temp.value < marker.next.value) {
                temp.next = marker.next;
                marker.next = temp;
                break;
            }

        }
        if (marker.next == null && temp.value > marker.value) {
                marker.next = temp;

            } 
    }

}