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

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

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
		if(pHead1 == nullptr || pHead2 == nullptr){
			return nullptr;
		}
        ListNode *cur1=pHead1;
        ListNode *cur2=pHead2;
		int n=0;
		while(cur1->next ){
			cur1 = cur1->next;
			n++;
		}
		while(cur2->next ){
			cur2 = cur2->next;
			n--;
		}
		if(cur1 != cur2){
			return nullptr;
		}
		cur1 = n>0 ? pHead1:pHead2;
		cur2 = cur1==pHead1?pHead2:pHead1;
		n = abs(n);
		while(n){
			cur1=cur1->next;
			n--;
		}
		while(cur1 != cur2){
			cur1 = cur1->next;
			cur2 = cur2->next;
		}
		return cur1;
	}
};

全部评论

相关推荐

阿武同学:基本信息保留前面三行,其他的可以全部删掉,邮箱最重要的你没写,主修课程精简到8个以内,实习里面2/3/4都是水内容的,非要写的话建议两到三句话,项目经历排版优化下,自我评价缩到三行
点赞 评论 收藏
分享
用微笑面对困难:只要你保证项目和获奖都是真的就行尤其是“对战,总负责人”啊这些套职,基本上队员,打杂的都这么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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