相交链表(leetcode)

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

struct ListNode* pf = headA;

struct ListNode* pd;

struct ListNode* str;

int i = 0;

while( pf != NULL )

{

for( pd = headB ; pd != NULL ; pd = pd->next )

{

if( pf == pd )

{

for( str = pf ; pd != NULL ; pd = pd->next , str = str->next )

{

if( str == pd )

{

;

}

else

goto end;

}

if( str == NULL )

return pd;

}

end:

}

pf = pf->next;

}

return NULL;

}

由于使用了三层循环嵌套:导致时间复杂度O(n^3)过高

改进:

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

struct ListNode *a = headA;

struct ListNode *b = headB;

struct ListNode *shortnode;

struct ListNode *longnode;

int len_a = 1;

int len_b = 1;

int i = 0;

while( a->next != NULL )

{

a = a->next;

len_a++;

}

while( b->next != NULL )

{

b = b->next;

len_b++;

}

if( a == b )

{

if( len_a > len_b )

{

shortnode = headB;

longnode = headA;

}

else

{

shortnode = headA;

longnode = headB;

}

for( i = 0 ; i < abs(len_a-len_b) ; i++)

{

longnode = longnode->nest;

}

while( longnode != shortnode )

{

longnode = longnode->next;

shortnode = shortnode->next;

}

return longnode;

}

else

{

return NULL;

}

}

时间复杂度:O(n);

相关推荐
伊玛目的门徒6 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
想做小南娘,发现自己是女生喵8 小时前
【无标题】
数据结构·算法
旖-旎10 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
凤凰院凶涛QAQ12 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
郝学胜-神的一滴13 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe13 小时前
算法滑动窗口
数据结构·算法
怪兽学LLM13 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
退休倒计时14 小时前
【每日一题】LeetCode 39. 组合总和 TypeScript
算法·leetcode·typescript
Scabbards_14 小时前
面试Leetcode - Array
leetcode·面试·职场和发展
LuminousCPP16 小时前
C 语言集中实践全记录:顺序表 + 单链表原理实现与通讯录项目实战【附可运行源码】
c语言·开发语言·数据结构·经验分享·笔记