相交链表(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);

相关推荐
ATAOL32 分钟前
数据结构一
数据结构·算法
罗超驿2 小时前
Java数据结构_链表
java·数据结构·链表
We་ct3 小时前
LeetCode 79. 单词搜索:DFS回溯解法详解
前端·算法·leetcode·typescript·深度优先·个人开发·回溯
眼眸流转3 小时前
LeetCode热题100(四)
算法·leetcode·职场和发展
AMoon丶4 小时前
Golang--多种数据结构详解
linux·c语言·开发语言·数据结构·c++·后端·golang
啊哦呃咦唔鱼4 小时前
LeetCode hot100-3 无重复字符的最长子串
算法·leetcode·职场和发展
宵时待雨5 小时前
C++笔记归纳10:继承
开发语言·数据结构·c++·笔记·算法
一叶落4385 小时前
LeetCode 21. 合并两个有序链表(C语言详解 | 链表经典题)
c语言·数据结构·c++·算法·leetcode·链表
阿里嘎多哈基米5 小时前
速通Hot100-Day04——哈希
数据结构·算法·leetcode·哈希算法·散列表
WolfGang0073215 小时前
代码随想录算法训练营 Day10 | 栈与队列 part02
数据结构