-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path408-2012-BF.cpp
More file actions
93 lines (88 loc) · 2.24 KB
/
Copy path408-2012-BF.cpp
File metadata and controls
93 lines (88 loc) · 2.24 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <cstdio>
#include <cstring>
using namespace std;
// 定义单链表数据结构
typedef char ElementType;
typedef struct Node
{
ElementType data;
struct Node *next;
Node(ElementType data)
{
this->data = data;
next = NULL;
}
} *List, LNode;
int main()
{
// input:
ElementType in1[] = {'l', 'o', 'a', 'd'}; // 单链表1中的值
ElementType in2[] = {'b', 'e'}; // 单链表2中的值
ElementType shared[] = {'i', 'n', 'g'};
int inSize1 = sizeof(in1) / sizeof(in1[0]);
int inSize2 = sizeof(in2) / sizeof(in2[0]);
int inSize3 = sizeof(shared) / sizeof(shared[0]);
// initialization:
List list1 = new LNode(0); // head node
List list2 = new LNode(0); // head node
List sharedList = new LNode(0);
// init shared part
List tail = sharedList;
for (int i = 0; i < inSize3; i++)
{
List node = new LNode(shared[i]); // 插入结点
tail->next = node;
tail = node;
}
// init list1
tail = list1;
for (int i = 0; i < inSize1; i++)
{
List node = new LNode(in1[i]); // 插入结点
tail->next = node;
tail = node;
}
tail->next = sharedList->next;
// init list2
tail = list2;
for (int i = 0; i < inSize2; i++)
{
List node = new LNode(in2[i]); // 插入结点
tail->next = node;
tail = node;
}
tail->next = sharedList->next;
// algorithm:
List ptr1 = list1, ptr2;
List res = NULL; // 存储结果
// 直接上暴力写法!两层循环,扫就完事了
while (ptr1 && !res)
{
ptr2 = list2;
while (ptr2 && !res)
{
if (ptr1 == ptr2)
res = ptr1;
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
// output:
if (!res)
printf("No matched results.\n");
else
{
printf("Addr:%p, Shared part:\n\t", res);
while (res)
{
printf("-> %c ", res->data);
res = res->next;
}
printf("\n");
}
}
/*
这题第一眼没想到很好的优解,考试的时候可没时间慢慢想,直接上两层循环暴力!
时间复杂度O(n^2),空间复杂度O(1)
- SomeBottle 2023.8.4
*/