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

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

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

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

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
#include <stdbool.h>
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    if(pHead1 == NULL || pHead2 == NULL){
        return  NULL;
    }
    struct ListNode* nodea = pHead1;
    struct ListNode* nodeb = pHead2;
    int n = 0;

    while(nodea != nodeb){
        nodea = nodea -> next;
        nodeb = nodeb -> next;
        if(nodea == NULL){
            nodea = pHead2;
            n += 1;
        }
        if (nodeb == NULL) {
            nodeb = pHead1;
            n += 1;
        }
        if (n >= 3) {
            return  NULL;
        }
    }

    return nodea;

    
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务