我是靠谱客的博主 鲜艳黑夜,这篇文章主要介绍【leetcode】求两个链表的交点,现在分享给大家,希望可以做个参考。

求两个链表的交点

c++
借助set

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        std::set<ListNode*>node_set;
        while(headA)
        {
            node_set.insert(headA);
            headA=headA->next;
        }
        while(headB)
        {
            if (node_set.find(headB)!=node_set.end())
                return headB;
            headB=headB->next;
        }
        return NULL;
    }
};

在这里插入图片描述

数学思维:

方法一

两人同时出发,相同的速度,先走自己的路,再走别人的路,走过的总路程一样,则一定会在交点处相遇,一起走向终点。
在这里插入图片描述

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* PA=headA;
    struct ListNode* PB=headB;
    if (headA==NULL||headB==NULL)
       { 
           printf("aaaa");
            return NULL;
        }
    else{
            while(PA!=PB)
                {          
                    PA=PA==NULL?headB:PA->next;
                    PB=PB==NULL?headA:PB->next;
                }
                    return PA;
        }
}

在这里插入图片描述
方法二:
思路:
先把长链表多出来的节点去掉。
当两个链表的长度相同后,再开始以相同的速度分别遍历两个链表。
在这里插入图片描述

int get_list_length(ListNode *head){
    int list_len=0;
    while(head){
        list_len+=1;
        head=head->next;
    }
    return list_len;
}
ListNode* move(int long_length,int short_length,ListNode* head)
{
    int move_step=long_length-short_length;
    while(move_step&&head){
        head=head->next;
        move_step-=1;
    }
    return head;
}
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA=get_list_length(headA);
        int lenB=get_list_length(headB);
        if (lenA>lenB){
            headA=move(lenA,lenB,headA);
        }
        else{
            headB=move(lenB,lenA,headB);
        }
        while(headA&&headB){
            if (headA!=headB){
                headA=headA->next;
                headB=headB->next;
            }
            else
                return headA;
        }
        return NULL;
    }
};

在这里插入图片描述

最后

以上就是鲜艳黑夜最近收集整理的关于【leetcode】求两个链表的交点的全部内容,更多相关【leetcode】求两个链表内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部