序言
今天总结一下交叉列表怎么如何找到交叉点?
一、思路概述
方法一:
- 分别定义两个指针变量p1和p2。
- 以p1为基准,遍历p2。
- 假设遍历完p2一遍后没有找到交叉点。
- p1后移一个节点,然后再遍历p2列表。
- 这样依次遍历两个列表,如果找到返回节点的值,若没有找到返回-1。
代码示例
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
} Node;
int findCommen(Node* list1, Node* list2) {
Node* p1 = list1;
Node* p2 = list2;
while(p2 != NULL) {
for(p1 = list1; p1 != NULL; p1 = p1 -> next) {
if (p1 == p2) {
return p1 -> value;
}
}
p2 = p2 -> next;
}
return -1;
}
int main() {
int value = 0;
Node n1, n2, n3, n4, n5, n6, n7;
n1.value = 1;
n2.value = 2;
n3.value = 3;
n4.value = 4;
n5.value = 5;
n6.value = 6;
n7.value = 7;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = NULL;
n7.next = &n4;
Node* p1 = &n1;
Node* p2 = &n7;
value = findCommen(p1, p2);
if (value == -1)
{
printf("No intersection");
} else {
printf("The value of the intersection point is %d\n", value);
}
return 0;
}
运行结果
总结
用这种方法虽然实现起来比较简单,但是时间复杂度比较高。
因为我们在寻找交叉点的时候,其中一个列表每遍历一个节点另一个列表就要全部遍历一遍。
所以假设列表一有m个节点;列表二有n个节点
则时间复杂度为O(m * n)
方法二:
- 首先分别遍历两个列表得到列表的长度。
- 计算两个列表的长度差。
- 将长的那个列表先往后移动两个列表差值的节点。
- 这样两个列表就一样长了,然后同时遍历两个列表。
- 找到交叉点就返回该节点对应的值。
代码示例
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
} Node;
//计算列表的长度
int listCount(Node* list) {
Node* p = list;
int i = 0;
while(p != NULL) {
p = p -> next;
i++;
}
return i;
}
//使两个列表的长度相等
Node* creatCommen(Node* list, int offSet) {
Node* p = list;
for (int i = 0; i < offSet; ++i)
{
p = p -> next;
}
return p;
}
//遍历两个列表返回交叉点的值
int findCommen(Node* list1, Node* list2) {
int longth1 = listCount(list1);
int shorth2 = listCount(list2);
Node* longlist = list1;
Node* shortlist = list2;
Node* p1 = NULL;
if (shorth2 > longth1)
{
longlist = list2;
shortlist = list1;
}
int offSet = abs(longth1 - shorth2);
if (offSet == 0)
{
p1 = longlist;
} else {
p1 = creatCommen(longlist, offSet);
}
Node* p2 = shortlist;
while(p1 != NULL) {
if (p1 == p2)
{
return p1 -> value;
}
p1 = p1 -> next;
p2 = p2 -> next;
}
return -1;
}
int main() {
int value = 0;
Node n1, n2, n3, n4, n5, n6, n7;
n1.value = 1;
n2.value = 2;
n3.value = 3;
n4.value = 4;
n5.value = 5;
n6.value = 6;
n7.value = 7;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = NULL;
n7.next = &n4;
Node* p1 = &n1;
Node* p2 = &n7;
value = findCommen(p1, p2);
if (value == -1)
{
printf("No intersection");
} else {
printf("The value of the intersection point is %d\n", value);
}
return 0;
}
运行结果
总结
用这种方法相比较第一种方法降低了时间复杂度。
只有在刚开始的时候遍历了两个列表,然后就开始找,找到就返回。
假设列表一有m个节点;列表二有n个节点。
则时间复杂度为O(m + n)。