Given two sorted linked lists, L1 and L2, a solution to compute their intersection L1 intersection L2.
L1_node = L1.head;
L2_node = L2.head;
Result = new SList;
while L1_node != NULL and L2_node != NULL:
if L1_node.value == L2_node.value:
Result.append(L1_node.value)
L1_node = L1_node.next
L2_node = L2_node.next
elif L1_node.value < L2_node.value:
L1_node = L1_node.next
else
L2_node = L2_node.next
(Translate to C yourself.)
The basic approach to in-order merge-like algorithms is that you never need to consider more than three items at a time - the front items from each input list, plus potentially a saved result.
In this case, I'd use...
loop forever
while in1.value < in2.value : transfer item from in1 to output
while in2.value < in1.value : transfer item from in2 to output
if in1.value == in2.value :
transfer item from in1 to output
discard item from in2
while in1.value == value just transferred : disard item from in1
while in2.value == value just transferred : disard item from in2
Now the nasty - this loop assumes the lists are infinite. How do you handle empty lists? That's fiddly, unless you can reserve a sentinel value which is greater than any legal value that can occur in the list.
If you can't reserve a sentinel, you can fake the effect - write a compare function that checks whether there's a next item in each queue before comparing values, and treats "queue exhausted" as implying the sentinel value.
That gives...
loop forever
while in1.value < in2.value : discard item from in1
while in2.value < in1.value : discard item from in2
if in1 exhausted, break out of loop
if in2 exhausted, break out of loop
if in1.value == in2.value :
transfer item from in1 to output
discard item from in2
while in1.value == value just transferred : discard item from in1
while in2.value == value just transferred : discard item from in2
OOPS
This is a union. Converting to an intersection is left as an exercise for the reader.
EDIT
OK - it is now an intersection. Just discarding the less-than items rather than adding them to the output. Also fixed a typo.
Note - my interpretation was that the output of an intersection should be a set, meaning no duplicates. This tolerates duplicates in the inputs, but the output is duplicate-free.