【发布时间】:2013-07-18 16:42:34
【问题描述】:
我正在尝试合并两个排序的链表。
代码 sn-p 不适用于以下两个列表:
List 1 : 1->3->5->7->9->null
List 2 : 2->4->6->8->10->null
Expected List : 1->2->3->4->5->6->7->8->9->10->null
但是下面程序的输出结果是这样的:
Output : 1->2->3->4->5->6->7->8->9->null // element 10 is missing.
我错过了什么吗?现场演示:http://ideone.com/O7MBlo
class Node {
Node next;
int value;
Node(int val) {
this.value = val;
this.next = null;
}
@Override
public String toString() {
Node cur = this;
String str = "";
while(cur != null) {
str += cur.value+"->";
cur = cur.next;
}
return str;
}
}
class MergeLL {
public static Node merge(Node n1, Node n2) {
Node result = null;
if(n1 != null && n2 != null) {
if(n1.value < n2.value) {
result = n1;
result.next = merge(n1.next, n2);
} else {
result = n2;
result.next = merge(n1, n2.next);
}
}
return result;
}
public static void main(String[] args) {
Node n1 = new Node(1);
Node n3 = new Node(3);
Node n5 = new Node(5);
Node n7 = new Node(7);
Node n9 = new Node(9);
n1.next = n3;
n3.next = n5;
n5.next = n7;
n7.next = n9;
n9.next = null;
Node n2 = new Node(2);
Node n4 = new Node(4);
Node n6 = new Node(6);
Node n8 = new Node(8);
Node n10 = new Node(10);
n2.next = n4;
n4.next = n6;
n6.next = n8;
n8.next = n10;
n10.next = null;
System.out.println("Merge : " + merge(n1, n2));
}
}
【问题讨论】:
-
如何将所有元素添加到单个集合中,对其进行排序然后循环以更新属性
next? -
@ArnaudDenoyelle:排序是 O(n log n)。直接合并是 O(n)。当你拥有一百万件物品时,差异是巨大的。
-
顺便说一句,递归合并有一个巨大的缺点:堆栈空间。如果没有尾递归删除,递归合并将消耗 O(n) 堆栈帧。因此,如果列表中的项目总数相当大(例如,100,0000 左右),您可能会破坏堆栈。
标签: java algorithm data-structures linked-list mergesort