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

相关推荐
_OP_CHEN5 小时前
C++基础:(十二)list类的基础使用
开发语言·数据结构·c++·stl·list类·list核心接口·list底层原理
Lris-KK9 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
坚持编程的菜鸟10 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
(●—●)橘子……10 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon10 小时前
LeetCode - 1171.
算法·leetcode·链表
iナナ10 小时前
Java优选算法——位运算
java·数据结构·算法·leetcode
Han.miracle11 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
筱砚.11 小时前
【数据结构——最小生成树与Kruskal】
数据结构·算法
蒙奇D索大13 小时前
【数据结构】考研数据结构核心考点:平衡二叉树(AVL树)详解——平衡因子与4大旋转操作入门指南
数据结构·笔记·学习·考研·改行学it
im_AMBER14 小时前
数据结构 04 栈和队列
数据结构·笔记·学习