![]() |
VOOZH | about |
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Example:
Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in both the list so they appear in the intersection list. Input: First linked list: 1->2->3->4->5 Second linked list be 2->3->4, Output: 2->3->4 The elements 2, 3, 4 are common in both the list so they appear in the intersection list.
: Using Dummy Node.
Approach:
The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either 'a' or 'b' and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.
Below is the implementation of the above approach:
Linked list containing common items of a & b 2 4 6
Complexity Analysis:
: Using Local References.
Approach: This solution is structurally very similar to the above, but it avoids using a dummy node Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If the list is built at its tail, either the dummy node or the struct node** "reference" strategy can be used.
Below is the implementation of the above approach:
Linked list containing common items of a & b 2 4 6
Complexity Analysis:
: Recursive Solution.
Approach:
The recursive approach is very similar to the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists.
Below is the implementation of the above approach:
Linked list containing common items of a & b 2 4 6
Complexity Analysis:
Use Hashing
0 3 4 5 6 7
Complexity Analysis:
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf