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

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

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
  public:
    int GetListLen(ListNode* pHead) {
        int len = 0;
        while (pHead) {
            len += 1;
			pHead = pHead->next;
        }
		return len;
    }
    ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
		int len1 = GetListLen(pHead1);
		int len2 = GetListLen(pHead2);
		int diff = abs(len1 - len2);	// 获取两个链表长度差

	  	// 确定长链表的头,先走diff步
		ListNode* pLonger = pHead1;
		ListNode* pShorter = pHead2;
		if (len2 > len1) {
			pLonger = pHead2;
			pShorter = pHead1;
		}

		while (diff-- > 0) {
			pLonger = pLonger->next;
		}

		while (pLonger && pShorter && pLonger != pShorter) {
			pLonger = pLonger->next;
			pShorter = pShorter->next;
		}

		return pLonger;	
    }
};

2023 剑指-链表 文章被收录于专栏

2023 剑指-链表

全部评论

相关推荐

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