当前位置:网站首页>力扣160. 相交链表
力扣160. 相交链表
2022-06-21 16:53:00 【SS_zico】
- 相交链表
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
题解
定义两个指针,分别向尾走
当两个指针走到尾时 就分别走对方的路 所有路程加起来 a+c+b == b+c+a 所以两个节点相交,则两个指针必定在相交节点相遇
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *A = headA,*B = headB;
while(A != B)
{
A = A != nullptr ? A = A->next : headB;
B = B != nullptr ? B = B->next : headA;
}
return A;
}
};
时间复杂度 : O(m+n)。
空间复杂度 : O(1)。
边栏推荐
- AI writes its own code to let agents evolve! The big model of openai has the flavor of "human thought"
- System V IPC与POSIX IPC
- Performance test ---locust's on_ Start and on_ Stop method
- PHP连接Mysql8.0报错:Illuminate\Database\QueryException
- C language DLL Dynamic Link Library
- PHP的empty,isset和is_null区别
- Redis6.0 new features (Part 1)
- 堆栈认知——栈溢出实例(ret2text)
- 有哪些好用的工作汇报工具
- Vit is crazy, 10+ visual transformer model details
猜你喜欢
随机推荐
AttributeError: ‘Book‘ object has no attribute ‘sheet‘
现有需求同步其他数据库用户信息到我们系统他们主键id为string我们主键为Long
PHP的empty,isset和is_null区别
aws elastic beanstalk入门之简介
Viewing technological changes through Huawei Corps (IV): interactive media (Music)
我被变相降薪了
2022低压电工考试题模拟考试题库及答案
Interceptor to realize web user login
Node的json解析
The source code of the online live broadcast system enables you to request the list interface and touch the bottom page to load
Show you how to distinguish several kinds of parallelism
Typescript接口
POSIX信号量
Technical architecture of large websites | information encryption technology and key security management
快速失败和安全失败的区别
Lua导出为外部链接库并使用
Can I use line as a product term in the cable industry? Generally not used
CentOS使用composer install 报错 - phpunitphpunit 8
小程序的宿主环境、组件、API、协同工作和发布
国元期货开户可靠吗?新手如何安全开户?





![[pwn基础]Pwntools学习](/img/67/6fb8a9628d5b750b0396f083aaeb91.png)



