Trying to self-learn Linked Lists, I stumbled upon a merging algorithm:
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;
}
courtesy of : https://stackoverflow.com/a/13886252/6630382
While I understand the logic for the most part, I am confused about: 1. Why do we need to declare "Node current"? Unless I am forgetting something about aliasing, wouldn't we be okay just using the Node head all the way through?
- Is there some sort of prerequisite needed for the merged list? Would we have to pre-define a list of size list1 + list2 or would this just build the list from scratch?
Thank you so much!