当前位置:网站首页>LeetCode Algorithm 剑指 Offer 52. 两个链表的第一个公共节点
LeetCode Algorithm 剑指 Offer 52. 两个链表的第一个公共节点
2022-06-24 19:38:00 【Alex_996】
题目链接:剑指 Offer 52. 两个链表的第一个公共节点
Ideas
算法:双指针+数学
数据结构:链表
思路:这道题我记得在左神算法初级班的时候讲过,有点忘记了,做法是两个指针都往前走,如果pa到头了就挪到pb,如果pb到头了就挪到pa,最后肯定会相遇,但是为什么会相遇的证明有点忘记了。我这里提供的算法是双指针加上一点点数学。首先考虑边界情况,如果两个指针中有一个为空,那么肯定没有相交的节点,直接
return nullptr就OK了。
然后需要计算出两个链表的长度lenA和lenB以及长度差diff,然后需要重新定义一下,让A表示长链表,B表示短链表。
如果两个链表有相交的部分,那么长出来的一块肯定是在不相交的那一部分,因为转换完了之后A比较长,所以指向A的指针可以先走diff步,然后两个指针再一起走,如果相等了,那就说明找到了第一个相交的节点,否则说明两个链表没有相交的部分。
Code
C++
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
int lenA = 0, lenB = 0;
ListNode *pA = headA, *pB = headB;
while (pA != nullptr) {
lenA++;
pA = pA->next;
}
while (pB != nullptr) {
lenB++;
pB = pB->next;
}
int diff = abs(lenA - lenB);
// 如果链表B的长度大于链表A的长度,交换A、B
if (lenB > lenA) {
pA = headA;
headA = headB;
headB = pA;
}
// headA先走diff步
for (int i = 0; i < diff; i++) {
headA = headA->next;
}
while (headA != nullptr) {
if (headA == headB) {
return headA;
} else {
headA = headA->next;
headB = headB->next;
}
}
return nullptr;
}
};
边栏推荐
- 网上立案流程
- 04A interrupt configuration
- CDN principle
- Seven principles of software design
- The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode
- Envoy obtain the real IP address of the client
- ThreadLocal内存泄漏问题
- 结构体的内存对齐
- How to compare two or more distributions: a summary of methods from visualization to statistical testing
- Fanuc robot_ Introduction to Karel programming (1)
猜你喜欢

AQS源码分析

The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode

Redis-跳表

YGG 近期游戏合作伙伴一览

In the era of full programming, should I give up this road?

2022-06-10 工作记录--JS-获取到某一日期N天后的日期
How to solve the problem that the computer suddenly can't connect to WiFi

ThreadLocal memory leak

Power system | IEEE paper submission process

Raspberry pie preliminary use
随机推荐
堆内存分配的并发问题
[ingénierie logicielle] points clés à la fin de la période
Basic principles of layer 2 switching
结构体的内存对齐
Principle of IP routing
Introduction, installation and use of postman tool
Web security XSS foundation 06
堆內存分配的並發問題
YGG recent game partners list
HTTP的缓存控制
NIO 零拷贝
Structure du disque
NIO、BIO、AIO
In the era of industrial Internet, there is no Internet in the traditional sense
nuScenes——数据集配置过程中遇到图像文件缺失或大小为0时的补救方法
Web攻击之CSRF和SSRF
Unable to use the bean introduced into the jar package
Information update on automatic control principle
In the first year of L2, arbitrum nitro was upgraded to bring more compatible and efficient development experience
CDN principle