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

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

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) {
        auto list_count = [](ListNode* node) -> int {
			int i = 0;
			while (node != nullptr) {
				++i;
				node = node->next;
			}
			return i;
		};

		int list1_node_count = list_count(pHead1);
		int list2_node_count = list_count(pHead2);
		if (list1_node_count == 0 || list2_node_count == 0) {
			return nullptr;
		}

		ListNode* p = pHead1;
		ListNode* q = pHead2;
		if (list1_node_count > list2_node_count) {
			for (int i = 0; i < list1_node_count - list2_node_count; ++i) {
				p = p->next;
			}
		} else {
			for (int i = 0; i < list2_node_count - list1_node_count; ++i) {
				q = q->next;
			}
		}

		while (p != q) {
			p = p->next;
			q = q->next;
		}
		if (p == nullptr) {
			return nullptr;
		} else {
			return p;
		}
    }
};

全部评论

相关推荐

牛客33727151号:不是哥们我以为驾照是段子呢
点赞 评论 收藏
分享
xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务