I am creating a function that takes two sorted linked lists and merges them into a combined linked list. Here are my two implementations. Only the second one works in all cases I have tested. Left and right are the lists, front() returns the data in the node the head pointer points to, pushBack() adds a new node to the end of the list, and popFront() deletes the node at the front of the list. Merged is the new list they are combined into.
Implementation 1:
else { if ((left.front() = right.front())) { merged.pushBack(left.front()); left.popFront(); merged.pushBack(right.front()); right.popFront(); } else if (left.front() < right.front()) { merged.pushBack(left.front()); left.popFront(); } else { merged.pushBack(right.front()); right.popFront(); } }
Implementation 2:
else { int leftFront = left.front(); int rightFront = right.front(); if (leftFront == rightFront) { merged.pushBack(leftFront); left.popFront(); merged.pushBack(rightFront); right.popFront(); } else if (leftFront < rightFront) { merged.pushBack(leftFront); left.popFront(); } else { merged.pushBack(rightFront); right.popFront(); } }
It makes sense to me that I should not be using the member functions in control statements or as function arguments, since they are not static and might change during runtime, but I cannot see for the life of me why, in this particular situation I get different results.
In one test, with left = [1, 5, 10, 20] and right = [2, 4, 11, 19], the merge produces the list merged = [2, 2, 4, 4, 11, 11, 19, 19]. Obviously incorrect, but I don't see why it can't even get the first comparison correct. As far as I can tell, the else if is going to evaluate if 1 < 2, it is, and then push 1 to the back of merged, and then delete 1.
In the future I will follow implementation 2, as it seems safer to me, but I am confused why method 1 does not work in this situation
https://stackoverflow.com/questions/67411284/is-it-in-general-wisest-to-not-use-member-functions-in-control-statements-functi May 06, 2021 at 11:06AM
没有评论:
发表评论