在链接的线性列表中插入新元素,对所有元素进行排序

时间:2014-05-06 21:26:20

标签: java linked-list singly-linked-list

我在 java

中有这段代码
public ListOfInt fillPairs() {
    ListOfInt r = new ListOfInt();
    // Auxiliad node for 'r'
    r.data = new Node();
    Node p = r.data; // new first value for 'r'
    // if this.data is null, the list is empty
    if (data == null) {
        return r;
    }
    // Copy the new list the existing elements of this.list
    Node i = data;
    p.value = i.value; // Always the first element
    while (i.next != null) {
        i = i.next;
        Node sig = new Node();
        sig.value = i.value;
        p.next = sig;
        p = sig;
    }
    Node last = i; // Store the last element
    // For each missing value we insert the new one
    for (int c = data.value + 1; c <= last.value; c++) {
        // We iterate the list every time to find the place for new element
        Node prev = null;
        Node j = r.data;
        if (c % 2 == 0) { // If new element value is not even, we keep on
            while (j != null && j.value < c) { // We get previous position
                prev = j;
                j = j.next;
            }
            Node sig = new Node();
            sig.value = c;
            sig.next = j;
            prev.next = sig;
        }
    }
    return r;
}

所有代码都经过评论,所以我认为毫无疑问我在任何一步都要做什么,但我需要解释一下我的需求:

如果我有一个由this引用的列表,例如list(2,11,12),我需要{2}在此示例中从2到12(因为2是列表的开头,12是最后一个),但我的代码返回一个像fill elements which are not included and they are multiple by two的列表,我需要这个list(2,4,6,8,10,12,12),我知道11不是偶数,但它已经在列表中。

非常感谢你!

0 个答案:

没有答案