Hey guys!
I am reading a terse Programming book in which the solution to a linked-list problem is coded as shown below. The struct prototype used is:
1 2 3 4 5 6
|
template <typename T>
struct ListNode
{
T data;
shared_ptr<ListNode<T>> next;
};
|
Problem: Write a function that takes singly linked lists, L and F, and returns the merge of L and F. Your code should reuse the nodes from the lists provided as input. Your function should use O(1) additional storage. The only field you can change in a node is next.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
shared_ptr<ListNode<int>> MergeTwoSortedLists(shared_ptr<ListNode<int>> F, shared_ptr<ListNode<int>> L)
{
//Creates a placeholder for the result
shared_ptr<ListNode<int>> dummy_head(new ListNode<int>);
auto tail = dummy_head;
while (F && L)
AppendNode(F->data < L->data ? &F: &L, &tail);
if (F)
//Appends the remaining nodes of F
tail->next = F;
else if (L)
//Appends the remaining nodes of L
tail->next = L;
return dummy_head->next;
}
void AppendNode(shared_ptr<ListNode<int>>* node, shared_ptr<ListNode<int>>* tail)
{
(*tail)->next = *node;
*tail = *node; //Updates tail
*node = (*node)->next;
}
|
I do need some clarifications/explanations about the following please:
1. In
line 8
, why are &F and &L being passed to function
AppendNode
when, as formal parameters of function
MergeTwoSortedLists
, F and L were already pointers?
2. In
line 17
, why is
dummy_head->next
being returned and NOT just
dummy_head
?
3. In
line 22
, why are the asterisks
again qualifying the type of the formal parameters
node
and
tail
when, in my view,
shared_ptr<ListNode<int>>
already qualified them as pointers?
4. As a result of the confusion expressed in 3. above,
lines 24
and
26
are downright confounding! If
node
and
tail
were pointers, why are they dereferenced and
then simultaneously used with the member access operator arrow (->) symbol?? I would think -> is strictly used with pointers!
5. As a follow-up to 4. above, would function
AppendNode
still have worked correctly if all the asterisks were removed?