当前位置:网站首页>【160. 相交链表】
【160. 相交链表】
2022-06-22 19:41:00 【爱吃榴莲的喵星人】
一、题目描述
二、题目思路
思路一:暴力求解-穷举
依次取A链表中的每个节点跟B链表中的所有节点比较,如果有地址相同的节点,就是交点
时间复杂度O(N^2)
思路二:
1.尾节点相同就是相交,否则就不相交
2.求交点:长的链表先走(长度差)步,再同时走,第一个相同的就是交点
时间复杂度O(N)
三、题目代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode * listA = headA;
struct ListNode * listB = headB;
int lenA=1;int lenB=1;
while(listA->next)
{
listA=listA->next;
lenA++;
}
while(listB->next)
{
listB=listB->next;
lenB++;
}
if(listA != listB)
{
return NULL;
}
int gap=abs(lenA-lenB);
struct ListNode * longlist = headA;
struct ListNode * shortlist = headB;
if(lenA < lenB)
{
longlist = headB;
shortlist = headA;
}
while(gap--)
{
longlist=longlist->next;
}
while(longlist != shortlist)
{
longlist=longlist->next;
shortlist=shortlist->next;
}
return shortlist;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。
边栏推荐
- Three ways of extending ribbon to support Nacos weight
- Code to image converter
- uniapp小程序商城开发thinkphp6积分商城、团购、秒杀 封装APP
- Easyclick update Gallery
- AAAI 2022 | 传统GAN修改后可解释,并保证卷积核可解释性和生成图像真实性
- laravel+宝塔计划任务
- 百家讲坛 武则天
- 92-几个用match_recognize SQL写法示例
- Oracle system/用户被锁定的解决方法
- Resolved: can there be multiple auto incrementing columns in a table
猜你喜欢

R语言AirPassengers数据集可视化
Oracle system/用户被锁定的解决方法

Remote access to raspberry pie via the Internet.

How to realize @ person function in IM instant messaging

Introduction of Neural Network (BP) in Intelligent Computing

R language organdata dataset visualization

MySQL foundation - constraints

Understand the index of like in MySQL
![[observation] innovation in the software industry has entered a](/img/b8/232ce6bc41a4154f6c9d48b0819d8f.png)
[observation] innovation in the software industry has entered a "new cycle". How can we make a new start in the changing situation?

what? You can't be separated by wechat
随机推荐
MYSQL 几个常用命令使用
R 语言 wine 数据集可视化
2022团体程序设计天梯赛L1
R 语言USArrests 数据集可视化
R language Midwest dataset visualization
【剑指Offer】面试题44.数字序列中的某一位数字
R language usarrests dataset visualization
88-被广为流传的参数优化, 是蜜糖还是毒药?
理财产品在双休日可以赎回吗?
A detailed solution to mysql8.0 forgetting password
Easyclick fixed status log window
A Dynamic Near-Optimal Algorithm for Online Linear Programming
R语言penguins数据集可视化
Software testing - Test Case Design & detailed explanation of test classification
Introduction of Neural Network (BP) in Intelligent Computing
超快变形金刚 | 用Res2Net思想和动态kernel-size再设计 ViT,超越MobileViT
[proteus simulation] H-bridge drive DC motor composed of triode + key forward and reverse control
91-oracle普通表改分区表的几种方法
CVPR 2022 oral | video text pre training new SOTA, HKU and Tencent arc lab launched excuse task based on multiple-choice questions
苹果GCD源代码


