2013-04-11 55 views
1

我有一个ListElement对象的LinkedList,我想创建一个递归的方法,该方法添加新的节点,同时仍然保留列表的排序顺序。在排序后的LinkedList中添加一个元素

现在我有:

public static ListElement InsertList(ListElement head, ListElement newelem) { 

    if (head == null) { 
     head = newelem; 
     head.next = null; 
    } 
    else if (head.next == null) { 
     newelem.next = null; 
     head.next = newelem; 
    } 
    else if (head.value < newelem.value) { 
     newelem.next = head; 
     head = newelem; 
    } 
    else if (head.value >= newelem.value) { 
     head = head.next; 
     return InsertList(head, newelem); 
    } 
    return head; 
} 

而且我多次使用的代码调用它:

ListElement head = null; 
ListElement elem; 

// this block of code is repeated multiple times with values of 3, 8, 20, and 15 
elem - new ListElement(); 
elem.value = 6; 
head = InsertList(head, elem); 

输出如下:

6 
6 3 
8 6 3 
20 8 6 3 
15 8 6 3 

该输出正确的前三行,但之后,这一切都变得奇怪。任何人都可以请改进我的算法?我觉得像InsertList方法可以缩短了很多。谢谢!

+1

我看到2个问题,它是:1)我认为你需要,因为你的不覆盖的情况下,扭转你的第一个2个elseifs其中head.next为空,但newelem.value大于head.value。 2)如果你不应该重新分配头部,那么你最后还是最后的。 – DMulligan 2013-04-11 03:10:56

回答

1

head = head.next声明在你的第四个条件块被破坏head元素。我相信这应该改为

else if(head.value >= newelem.value) { 
    head.next = InsertList(head.next, newelem); 
} 
1

当您尝试插入15,你进入第4个条件:

// 20 > 15 
else if (head.value >= newelem.value) 

进而调用InsertList但作为头节点经过8,从而进入第三条件:

// 8 < 15 
else if (head.value < newelem.value) 

在这里,你说

newelem.next = head; 

这台15 - >未来= 8

,然后你说,

head = newelem; 

这台头= 15

你看这个问题?使用@ Zim-Zam O'Pootertoot答案来解决你的错误。

相关问题