c++ 取两个链表的交集
Problem statement: Write a C++ program to find the intersection of two single linked lists.
问题陈述:编写一个C ++程序来查找两个单个链表的交集。
Example:
例:
Let the first linked list be:
6->5->2->9->NULL
Let the second linked list to be:
2->7->NULL
So there intersection is:
2->NULL
Solution
解
Brute force approach:
蛮力法:
One technique can be to traverse all the nodes of a linked list and check whether the traversed node is in the other linked list or not. Such an approach takes O(m*n) times complexity. m, n=length of linked lists.
一种技术可以是遍历链表的所有节点,并检查遍历的节点是否在另一链表中。 这种方法需要O(m * n)乘以复杂度 。 m , n =链表的长度 。
Efficient approach:
高效的方法:
Efficient approach use to use merge sort.
高效的方法用于使用合并排序 。
Sort both the linked list using merge sort. ( for detailed refer to: Merge sort for single linked lists)
使用合并排序对两个链表进行排序。 (有关详细信息,请参阅: 合并单个链接列表的排序 )
Scan each linked list and build intersection according to following:
扫描每个链表并按照以下步骤建立交集:
IF (list1->data < list2->data) No intersection found Traverse list1 by one step( list1=list1->next) ELSE IF(list1->data ==list2->data) Createnode(list1->data) && append node to the intersection list