一、基本思路
- 分别求出两个链表的长度n和m。
- 假设长链表的长度为n,短链表的长度为m,令长链表先移动n-m步。
- 经过步骤2之后两个链表尾部对齐,此时同时向后移动,并判断是否有相同的结点。
二、代码实现
#include <iostream>
#include <vector>
using namespace std;
// int **p和int *&p的区别
// **p是指向(*p)的指针
// *&p是(*p)的引用
// 不能定义指向引用的指针,因为引用本身并不是一个对象,只是一个别名
struct Node {
int val;
Node *next;
Node(int v) {
val = v;
next = nullptr;
}
};
// 通过vector新建链表
Node *NewList(vector<int> &arr) {
Node *dummyHead = new Node(-1);
Node *cur = dummyHead;
for(int i = 0; i < arr.size(); i++) {
Node *node = new Node(arr[i]);
cur->next = node;
cur = cur->next;
}
return dummyHead;
}
// 释放链表
void DeleteList(Node *head) {
Node *cur = head;
while(cur != nullptr) {
Node *tmp = cur;
cout << tmp->val << endl;
cur = cur->next;
delete tmp;
tmp = nullptr;
}
}
// 构造测试数据
void build(Node *&list1, Node *&list2) {
vector<int> arr1{5, 6};
vector<int> arr2{9, 8, 8};
vector<int> arr3{1, 2, 3, 4};
list1 = NewList(arr1);
list2 = NewList(arr2);
Node *list3 = NewList(arr3);
Node *cur;
cur = list1;
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = list3->next;
cur = list2;
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = list3->next;
}
// 可视化链表结构
void print(Node *list) {
const Node *cur = list;
while(cur->next != nullptr) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
// 求链表长度
int len(Node *list) {
int cnt = 0;
const Node *cur = list;
while(cur->next != nullptr) {
cnt++;
cur = cur->next;
}
return cnt;
}
int main() {
Node *list1, *org1;
Node *list2, *org2;
build(list1, list2);
org1 = list1;
org2 = list2;
print(list1);
print(list2);
int n = len(list1), m = len(list2);
// 保证list1是长的链表
if(n < m) {
Node *tmp = list2;
list2 = list1;
list1 = tmp;
}
int step = abs(n-m);
while(step) {
step--;
list1 = list1->next;
}
while(list1 != list2) {
list1 = list1->next;
list2 = list2->next;
}
if(list1 == nullptr){
cout << "two list do not cross" << endl;
return 0;
}
cout << "two list cross at " << list1 << ", it's val is " << list1->val << endl;
// 使用如下方式释放内存时,虽然可以正常运行,但是
// 在释放的过程中,有野指针访问内存,实际使用过程中
// 可能发生意想不到的错误。
// DeleteList(org1);
// DeleteList(org2);
Node *tmp = org2;
while(tmp->next != list1) {
tmp = tmp->next;
}
tmp->next = nullptr;
DeleteList(org1);
DeleteList(org2);
return 0;
}
关于C++内存释放与野指针等问题,先在此挖个坑,希望以后有机会能想起来填上。