-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path37_FirstCommonNodesInLists.cpp
107 lines (94 loc) · 1.62 KB
/
37_FirstCommonNodesInLists.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX 1003
struct ListNode
{
int value;
ListNode *next;
};
ListNode *CreateList(ListNode **root, int n)
{
if (n <= 0)
return NULL;
*root = new ListNode;
ListNode *index;
int tmp;
cin >> tmp;
(*root)->value = tmp;
(*root)->next = NULL;
index = *root;
for (int i = 1; i < n; i++)
{
index->next = new ListNode;
index = index->next;
cin >> tmp;
index->value = tmp;
index->next = NULL;
}
return *root;
}
void DeletList(ListNode **root)
{
if (*root == NULL)
return;
ListNode *index = *root, *tmp;
while (index)
{
tmp = index->next;
delete index;
index = tmp;
}
}
int FindFirstCommonNode(ListNode *list1, ListNode *list2, int m, int n)
{
ListNode *index_long = NULL, *index_short = NULL;
int lon, sht;
if (m >= n)
{
lon = m;
sht = n;
index_long = list1;
index_short = list2;
}
else
{
lon = n;
sht = m;
index_long = list2;
index_short = list1;
}
for (int i = 0; i < lon - sht; i++)
index_long = index_long->next;
while ((index_long != NULL) && (index_short != NULL))
{
if (index_long->value != index_short->value)
{
index_long = index_long->next;
index_short = index_short->next;
}
else
break;
}
if (index_long != NULL && index_short != NULL)
cout << index_long->value << endl;
else
cout << "My God" << endl;
return 0;
}
int main(void)
{
int m, n;
while (cin >> m >> n)
{
ListNode *list1 = NULL;
ListNode *list2 = NULL;
CreateList(&list1, m);
CreateList(&list2, n);
FindFirstCommonNode(list1, list2, m, n);
DeletList(&list1);
DeletList(&list2);
}
return 0;
}