3 ms·
Nice little post. But I see a few problems. techgeeknet, is this code your work? Regardless, here is a critique. (1) The biggest problem is doing a "free" on a
by ggchappell 14y ago
Nice little post. But I see a few problems. techgeeknet, is this code your work? Regardless, here is a critique.
(1) The biggest problem is doing a "free" on a caller-provided pointer without giving any explicit requirements for where that pointer originated. It definitely needs to be stated up front that the nodes in the list referenced by list2 must have been individually allocated with "malloc".
Alternatively, the removed nodes could be returned to the caller in a separate list, which the caller could then deallocate.
(2) A somewhat similar issue is that the two input lists must have no nodes in common. Again, this needs to be stated.
(3) Variable names. I see "list1", "list2", "list", "tlist", and "dflag". What do these mean? I'm not sure. (OTOH "mergedlist" is good; that should be kept.)
(4) Efficiency. As noted at the bottom, this is a quadratic-time algorithm. True, it does make minimal assumptions about the type of "info". But with slightly stronger assumptions, the code could be a lot faster.
In particular, if the type of "info" is orderable, then do a Merge Sort on each of the input lists first. The resulting lists can be merged in linear time. So the whole algorithm would be log-linear time. And there would be no significant additional space requirements (if a non-recursive Merge Sort is used).
If the type can be hashed, then deplicates can be detected by inserting all values into a Hash Table. The resulting algorithm is still quadratic time, and it does require space for the Hash Table, but the average case is much faster: linear time.
- ternaryoperator 14y agoI think list1 and list2 are fine names. dflag presumably is a duplicate flag, and like the comments on the site point out, it's not needed. Agreed that sorting the lists would make the concatenation faster.