题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    //两个指针F与S同时遍历两个链表,如果F遍历到空就从另一个链表进行遍,S同样
    //这样就保证F和S会走相同的路程,如果没有焦点这个点就是空
    struct ListNode* F = pHead1;
    struct ListNode* S = pHead2;
    while(F != S)
    {
        F = (F == NULL)?pHead2:F->next;
        S = (S == NULL)?pHead1:S->next;

    }
    return F;
    

}

全部评论
@造子
1
送花
回复
分享
发布于 03-02 23:32 湖南

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务