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

相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll5 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐5 天前
leetcode-最小栈
java·算法·leetcode
岛雨QA5 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg15 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA5 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX5 天前
020-C++之unordered容器
数据结构·c++