尝试自学链接列表,我偶然发现了合并算法:
Node MergeLists(Node node1, node2)
{
if(node1 == null)
return node2;
else (node2 == null)
return node1;
Node head;
if(node1.data < node2.data)
{
head = node1;
node1 = node1.next;
else
{
head = node2;
node2 = node2.next;
}
Node current = head;
while((node1 != null) ||( node2 != null))
{
if(node1 == null) {
current.next = node2;
return head;
}
else if (node2 == null) {
current.next = node1;
return head;
}
if(node1.data < node2.data)
{
current.next = node1;
current = current.next;
node1 = node1.next;
}
else
{
current.next = node2;
current = current.next;
node2 = node2.next;
}
}
current.next = NULL // needed to complete the tail of the merged list
return head;
}
礼貌:https://stackoverflow.com/a/13886252/6630382
虽然我在很大程度上理解逻辑,但我很困惑: 1.为什么我们需要声明“节点当前”?除非我忘记了别名,否则我们不能只使用Node头一直通过吗?
非常感谢你!