当前位置:网站首页>【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;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。
边栏推荐
- SwiftUI如何模拟视图发光增大的动画效果
- Numpy learning notes (6) -- sum() function
- EasyClick 固定状态日志窗口
- Cross domain cors/options
- Software testing - Test Case Design & detailed explanation of test classification
- 阿里云视频点播播放出错,控制台访问出现code:4400
- R语言AirPassengers数据集可视化
- Lora technology -- Lora signal changes from data to Lora spread spectrum signal, and then from RF signal to data through demodulation
- 92-几个用match_recognize SQL写法示例
- Oh, my God, it's a counter attack by eight part essay
猜你喜欢
随机推荐
Feign常见问题总结
R language airpassengers dataset visualization
70-根因分析-oracle数据库突发性能问题,谁来背这个锅
从感知机到Transformer,一文概述深度学习简史
Résolu: peut - on avoir plus d'une colonne auto - incrémentale dans un tableau
uniapp小程序商城开发thinkphp6积分商城、团购、秒杀 封装APP
87-with as写法的5种用途
The real king of cache
Introduction of neural network (BP) in Intelligent Computing
密码学系列之:PKI的证书格式表示X.509
R 语言 wine 数据集可视化
78-生产系统不改代码解决SQL性能问题的几种方法
[in depth understanding of tcapulusdb technology] form creation and approval of document acceptance
已解决:一个表中可以有多个自增列吗
How to calculate the Gini coefficient in R (with examples)
LORA技术---LoRa信号从数据流变为LoRa扩频信号,再从射频信号通过解调变为数据
Is the brokerage account of qiniu delivery safe? Is the brokerage account provided by qiniu true?
laravel+宝塔计划任务
真正的缓存之王Caffine Cache
Ribbon load balancing












