大家好,我是蘇貝,本篇博客帶大家刷題,如果你覺得我寫的還不錯的話,可以給我一個贊👍嗎,感謝??
點擊查看題目
思路:
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {struct ListNode *cur1=headA;struct ListNode *cur2=headB;int len1=1;int len2=1;//1.找到兩個鏈表的最后一個節點while(cur1->next){cur1=cur1->next;len1++;} while(cur2->next){cur2=cur2->next;len2++;}//2.比較這兩個最后節點的地址,如果相同即存在相交節點,不同則不存在if(cur1!=cur2){return NULL;}//3.讓長的鏈表先走差距步struct ListNode *LongList=headA;struct ListNode *ShortList=headB;if(len1<len2){LongList=headB;ShortList=headA;}int len=abs(len1-len2);//求絕對值while(len--){LongList=LongList->next;}//一起走while(LongList!=ShortList){LongList=LongList->next;ShortList=ShortList->next;}return LongList;}
好了,那么本篇博客就到此結束了,如果你覺得本篇博客對你有些幫助,可以給個大大的贊👍嗎,感謝看到這里,我們下篇博客見??