xqn2017

导航

160. Intersection of Two Linked Lists

原文题目:

160. Intersection of Two Linked Lists

读题:

给定两个无环链表,判断是否有交叉点,返回第一个交叉点

解题思路:

求出两个链表长度lenA和lenB,得到两者的差值,deltaLen = lenA - lenB,这里假设A长度大于B长度,让p指向A头结点,q指向B头结点,此时,让p先往前走deltaLen个节点,这个时候p和q开始后面的长度,A和B是一样的,对齐之后开始比较p和q,有相等则就是第一个交点,没有的话就是无交点。AC代码如下:

class Solution 
{
public:
	ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 
	{
		int lenA = 0;
		int lenB = 0;
		int deltaLen = 0;
		int loop = 0;
		ListNode *p = headA;
		ListNode *q = headB;
		
		//链表A和B有一个为空,或者两个都为空,则无交点
		if(NULL == headA || NULL == headB)
		{
			return NULL;
		}
		//求链表A长度
		while(p)
		{
			lenA++;
			p = p->next;
		}
		//求链表B长度
		while(q)
		{
			lenB++;
			q = q->next;
		}
		//同时指向开始的头节点
		p = headA;
		q = headB;

		//如果A长度大于B,则将p往前走deltaLen
		if (lenA >= lenB)
		{
			deltaLen = lenA -lenB;
			while(deltaLen--)
			{
				p = p->next;
			}
			
			q = headB;
		}
		//如果A长度小于B,则将q往前走deltaLen
		else
		{
			deltaLen = lenB -lenA;
			p = headA;
			while(deltaLen--)
			{
				q = q->next;
			}
		}
		//对齐后剩下的节点进行比较
		while(p && q)
		{
			if(p == q)
			{
				return p;
			}
			p = p->next;
			q = q->next;
		}
		return NULL;
	}

}

int main()
{
	ListNode* result;
	Solution s;
	//构造链表A:1->2->3->4->7->8->9 B:5->6->7->8->9 公共节点为7,8,9,返回7
	ListNode* node1 = new ListNode(1);
	ListNode* node2 = new ListNode(2);
	ListNode* node3 = new ListNode(3);
	ListNode* node4 = new ListNode(4);
	ListNode* node5 = new ListNode(5);
	ListNode* node6 = new ListNode(6);
	ListNode* node7 = new ListNode(7);
	ListNode* node8 = new ListNode(8);
	ListNode* node9 = new ListNode(9);
	node1->next =node2;
	node2->next =node3;
	node3->next = node4;
	node4->next = node7;
	node7->next = node8;
	node8->next = node9;
	node5->next = node6;
	node6->next = node7;

	result = s.getIntersectionNode(node1,node5);
	cout<<result->val<<endl;
	
}

  

posted on 2017-12-08 19:11  xqn2017  阅读(145)  评论(0编辑  收藏  举报