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

相关推荐
散1128 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-19438 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww8 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚10 小时前
[数据结构] 排序
数据结构
_不会dp不改名_12 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌12 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun12 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌12 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long13 小时前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn13 小时前
Redis7底层数据结构解析
前端·数据结构·bootstrap