🕺作者: 主页
我的专栏 C语言从0到1 探秘C++ 数据结构从0到1 探秘Linux 算法题上机准备 😘欢迎 ❤️关注 👍点赞 🙌收藏 ✍️留言
题目
给定两个单链表,编写算法找出两个链表的公共结点。
算法思路
- 先将链表对齐,这样开始遍历后如果碰到节点相同就是公共节点
题解
c
int length(LinkedList L) {
LNode* p = L;
if (p == NULL) {
return 0;
}
int ans = 0;
while (p != NULL) {
p = p->next;
ans++;
}
return ans;
}
LNode* findCommon(LinkedList L1, LinkedList L2) {
int len1 = length(L1);
int len2 = length(L2);
LNode* longhead = len1 > len2 ? L1 : L2;
LNode* shorthead = longhead == L1 ? L2 : L1;
int diff = len1 - len2 > 0 ? len1 - len2 : len2 - len1;
while (diff > 0) {
longhead = longhead->next;
diff--;
}
while (longhead) {
if (longhead == shorthead) {
return longhead;
}
longhead = longhead->next;
shorthead = shorthead->next;
}
return NULL;
}