This repository has been archived by the owner on Mar 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
12.cpp
79 lines (70 loc) · 1.61 KB
/
12.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "ds.h"
/**
* 创建一个带有头节点的链表并返回
*/
List12 create_list12(const std::vector<char> &data) {
if (data.empty()) {
return NULL;
}
auto *head = (Node12 *) malloc(sizeof(Node12));
head->next = NULL;
Node12 *p = head;
for (char c: data) {
auto *cur = (Node12 *) malloc(sizeof(Node12));
cur->data = c;
cur->next = NULL;
p->next = cur;
p = cur;
}
return head;
}
/**
* 获取链表长度并返回
*/
int get_len(List12 list) {
int len = 0;
while (list->next != NULL) {
list = list->next;
len++;
}
return len;
}
/**
* 暴力解:双重循环,扫描A链表的同时对比B链表所有的结点,找到第一个共同点
*/
Node12 *find_common_bf(List12 A, List12 B) {
Node12 *pa = A->next, *pb = B->next;
while (pa != NULL) {
while (pb != NULL) {
if (pa == pb) {
return pa;
}
pb = pb->next;
}
pa = pa->next;
pb = B->next;
}
return NULL;
}
/**
* 最优解:获取两个链表的长度,右对齐,然后同时扫描,找到第一个共同点
*/
Node12 *find_common(List12 A, List12 B) {
int al = get_len(A), bl = get_len(B);
while (al > bl) {
A = A->next;
al--;
}
while (al < bl) {
B = B->next;
bl--;
}
while (A != NULL && B != NULL) {
if (A == B) {
return A;
}
A = A->next;
B = B->next;
}
return NULL;
}