160. Intersection of Two Linked Lists

         這道題很簡單,思路大概是找出最長的那個鏈表,然後長鏈表從頭開始除掉比短鏈表長的那一部分,當然不是刪掉,移動一下指針就行了,這樣下來兩個鏈表就對齊了。之後,一對一的比較,若相同就是交匯處,到遍歷完時,沒有找到交叉點,那就是空了。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
   int length(ListNode* head)
{
	ListNode* p=head;
	int count=0;
	while(p!=NULL)
	{
		count++;
		p=p->next;
	}
	return count;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
       
	ListNode *posShort,*posLong;
	int lengthA=length(headA);
	int lengthB=length(headB);
	if(lengthA>lengthB)
	{
		posShort=headB;
		posLong=headA;
	}
	else
	{
		posShort=headA;
		posLong=headB;
	}
	int distance=abs(lengthA-lengthB);
	while (distance>0)
	{
		posLong=posLong->next;
		distance--;
	}
	while (posLong!=NULL)
	{
		if(posLong->val==posShort->val)
			return posShort;
		posLong=posLong->next;
		posShort=posShort->next;
	}
	return NULL; 
}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章