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

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

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	int ListLen(ListNode* p) {
		int n=0;
		while(p) {
			p=p->next;
			n++;
		}
		return n;
	}
    ListNode* FindFirstCommonNode( ListNode* head1, ListNode* head2) {
		ListNode* p1=head1;
		ListNode* p2=head2;
		int len1=ListLen(p1);
		int len2=ListLen(p2);
		int gap=0;
		if(len1>len2) {
			gap = len1-len2;
			while(gap--) {
				p1=p1->next;
			}
		}else{
			gap = len2-len1;
			while(gap--) {
				p2=p2->next;
			}
		}
		while(p1 && p2) {
			if(p1->val == p2->val) return p1;
			p1=p1->next;
			p2=p2->next;
		}
		return nullptr;
    }
};

全部评论

相关推荐

debug 到凌晨 ...:还有这种雷霆提问,我都不懂这种提问何意味啊?“你为什么不用 Coze 直接拖一下?”“我:因为 Coze 适合标准化场景,业务复杂的时候要自己写……”;他:“那你写的不就是工作流吗?哪里 Agent 了?”;真给我干沉默了。。。 小公司做Agent真就挺草台的
想做Agent可以做哪些...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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