1. 程式人生 > 其它 >leetcode-相交連結串列-15

leetcode-相交連結串列-15

技術標籤:Linuxoj題

題目要求
  編寫一個程式,找到兩個單鏈表相交的起始節點。
思路
  先計算兩個連結串列的長度,如果兩個連結串列結束的結點不一樣,肯定不是相交連結串列,如果結束結點一樣,那肯定相交,計算兩個連結串列長度的差值,讓長的先走差值步,然後兩個連結串列同時向下走,進行比較,第一個相等的結點就是兩個連結串列相交的起始結點。
圖解
在這裡插入圖片描述
程式碼實現

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
	int lenA = 0, lenB = 0;
	struct ListNode* curA = headA;
	struct ListNode* curB = headB;

	while (curA)
	{
		curA = curA->next;
		lenA++;
	}

	while (curB)
	{
		curB = curB->next;
		lenB++;
	}

	if (curA != curB)
	{
		return NULL;
	}

	int n = abs(lenA - lenB);
	curA = headA;
	curB = headB;
	while (n--)
	{
		if (lenA > lenB)
		{
			curA = curA->next;
		}
		if (lenA < lenB)
		{
			curB = curB->next;
		}
	}

	while (curA != curB)
	{
		curA = curA->next;
		curB = curB->next;
	}

	return curA;
}