-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path7-52_两个有序链表序列的交集 (25).cpp
71 lines (63 loc) · 1.47 KB
/
7-52_两个有序链表序列的交集 (25).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
#include <iostream>
using namespace std;
class Node {
public:
Node *next;
int data;
Node(int data):data(data) { }
};
Node* BuildLinkList() {
int v;
Node *s = NULL, *tmp = NULL;
while (scanf("%d", &v) == 1 && v != -1) {
Node *node = new Node(v);
if (tmp == NULL) {
s = node;
tmp = node;
} else {
tmp->next = node;
tmp = tmp->next;
}
}
return s;
}
Node* IntersectLinkList(Node *s1, Node *s2) {
Node *s3 = NULL, *tmp = NULL, *node;
while (s1 != NULL && s2 != NULL) {
if (s1->data < s2->data) s1 = s1->next;
else if (s1->data > s2->data) s2 = s2->next;
else {
node = new Node(s1->data);
s1 = s1->next;
s2 = s2->next;
if (tmp == NULL) {
s3 = node;
tmp = node;
} else {
tmp->next = node;
tmp = tmp->next;
}
}
}
return s3;
}
int main() {
auto s1 = BuildLinkList();
auto s2 = BuildLinkList();
auto s3 = IntersectLinkList(s1, s2);
bool firstPrint = true;
if (s3 == NULL) printf("NULL\n");
else {
while (s3 != NULL) {
if (firstPrint) {
printf("%d", s3->data);
firstPrint = false;
} else {
printf(" %d", s3->data);
}
s3 = s3->next;
}
printf("\n");
}
return 0;
}