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

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

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

这是2021年的第一题,主要是找到链表长度这个工具,再根据双链表Y的形状,配合快慢指针,找到突破口。tt

/* struct ListNode { int val; struct ListNode next; ListNode(int x) : val(x), next(NULL) { } };/ //null表示符号 class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int L1 = GetLength(pHead1); int L2 = GetLength(pHead2);

		//move bigger 
		int step=0;
		ListNode *fast = NULL, *slow =NULL;
		if(L2 >=L1)
		{
			step = L2 - L1;
			fast=pHead2;
			slow=pHead1;

		}else{
			step = L1 - L2;
			fast=pHead1;
			slow=pHead2;
		
		}
		
		//等长比较
			while(step-- >0)
			{
				fast=fast->next;
			}
			while(fast!=slow && fast!=NULL && slow!=NULL ){
				fast=fast->next;
				slow=slow->next;
			}
			if(fast==NULL){
			return fast;}
			else{
				return fast;
			}
}


    int GetLength(ListNode* pH)
	{
		
		if(pH==NULL )return 0;
		
		int len=0;

		while(pH!=NULL){
			len++;
			pH=pH->next;
		}
        return len;

	
    }

};

全部评论
某某人 yi gao mei
点赞 回复 分享
发布于 2022-02-15 12:01

相关推荐

群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务