// 比较等长的列表元素,即可获得合并的元素
// 1. 链表长度确定
// 时间复杂度 O(max(m,n)), 空间复杂度是O(1)
list* find(list* l1, int l1_len, list* l2, int l2_len) {
list* l1_next = l1, *l2_next = l2;
if ( l1_len > l2_len) {
for (int i = 0; i < l1_len - l2_len; i++) {
l1_next = l1_next->next;
}
} else if (l1_len < l2_len) {
for (int i = 0; i < l2_len - l1_len; i++) {
l2_next = l2_next->next;
}
}
do {
if (l1_next == l2_next)
return l1_next;
l1_next = l1_next->next;
l2_next = l2_next->next;
} while(l1_next && l2_next);
assert(l1_next == l2_next);
assert(l1_next == NULL);
return NULL;
}
// 2.链表长度不确定
// 时间复杂度 O(2*max(m,n)) ,空间复杂度是O(1)
list* find(list* l1, list* l2) {
int l1_len, l2_len
list* l1_next = l1, *l2_next = l2;
list* tmp, *ttmp;
do {
if (l1_next == l2_next) {
return l1_next;
l1_next = l1_next->next;
l2_next = l2_next->next;
} while(l1_next && l2_next);
if (l1_next ==NULL && l2_next == NULL)
return NULL;
tmp = l1_next == NULL ? l2 : ll;
ttmp = l1_next == NULL ? l2_next : ll_next;
while (ttmp->next) {
tmp = tmp->next;
ttmp = ttmp->next;
}
if (l1_next == NULL) {
l2_next = tmp;
l1_next = l1;
} else {
l1_next = tmp;
l2_next = l2;
}
assert(l1_next);
assert(l2_next);
do {
if (l1_next == l2_next) {
return l1_next;
}
l1_next = l1_next->next;
l2_next = l2_next->next;
} while(l1_next && l2_next);
assert(l1_next == l2_next);
assert(l1_next == NULL);
return NULL;
}
评论