剑指offer67题-No36.两个链表的第一个公共节点

双指针算法

法1:

  1. 计算 List1List2 的长度 len1len2
  2. 让较长的链表的指针先走 |len1 - len2| 步。
  3. 然后两个指针一起走,直到相遇或到达 NULL
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    if( pHead1 == NULL || pHead2 == NULL) return NULL;
    struct ListNode* cur1 = pHead1;
    struct ListNode* cur2 = pHead2;
    int len1 = 0;
    int len2 = 0;
    // 让更长的先走 |len1-len2|步
    while(cur1 != NULL){
        ++len1;
        cur1 = cur1->next;
    }
    while(cur2 != NULL){
        ++len2;
        cur2 = cur2->next;
    }
    cur1 = pHead1;
    cur2 = pHead2;
    if(len1 > len2){
        while(len1 > len2){
            cur1 = cur1->next;
            len1--;
        }
    }else if(len2 > len1){
        while(len2 > len1){
            cur2 = cur2->next;
            len2--;
        }
    }
    while(cur1 != cur2){
        cur1 = cur1->next;
        cur2 = cur2->next;
    }
    return cur1;
}

法2:和法1差不多,直接走,有交点或者是都为NULL,就可以退出循环。

struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2) {
    if (pHead1 == NULL || pHead2 == NULL) return NULL;
    
    struct ListNode* cur1 = pHead1;
    struct ListNode* cur2 = pHead2;
    
    while (cur1 != cur2) {
        cur1 = (cur1 == NULL) ? pHead2 : cur1->next;
        cur2 = (cur2 == NULL) ? pHead1 : cur2->next;
    }
    return cur1; // 返回交点或NULL(无交点)
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇