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

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

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	int ListLength(ListNode* pHead) {
		int length = 0;
		if (pHead == nullptr) {
			return length;
		}

		ListNode* pNode = pHead;
		while (pNode != nullptr) {
			++length;
			pNode = pNode->next;
		}

		return length;
	}

    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int length1 = ListLength(pHead1);
		int length2 = ListLength(pHead2);

		int sub = length1 - length2;
		ListNode* pListHeadLong = pHead1;
		ListNode* pListHeadShort = pHead2;
		if (length1 < length2) {
			pListHeadLong = pHead2;
			pListHeadShort = pHead1;
			sub = length2 - length1;
		}

		for (int i = 1; i <= sub; ++i) {
			pListHeadLong = pListHeadLong->next;
		}

		while (pListHeadLong != nullptr && pListHeadShort != nullptr && pListHeadLong != pListHeadShort) {
			pListHeadLong = pListHeadLong->next;
			pListHeadShort = pListHeadShort->next;
		}

		return pListHeadLong;
    }
};

全部评论

相关推荐

码农索隆:想看offer细节
点赞 评论 收藏
分享
06-04 09:27
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 16:22
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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