标签:
这个题目较容易,我的想法是先比较两个链表的长度,我们要找到的交叉点是不可能为长的链表的前面超长的部分的,
所以要比较的就是两者之间较短的部分
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
null
./**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
size_t lengthA=0, lengthB=0,minus=0;
ListNode *pA=headA, *pB=headB,*IntersectionNode=NULL;
while (pA != NULL)
{
++lengthA;
pA = pA->next;
}
while (pB != NULL)
{
++lengthB;
pB = pB->next;
}
if (lengthA > lengthB)
{
pA = headA;
pB = headB;
minus = lengthA - lengthB;
while (minus--)
{
pA = pA->next;
}
while (pA != NULL&&pB != NULL)
{
if (pA->val == pB->val&&IntersectionNode==NULL)
IntersectionNode = pA;
if (pA->val != pB->val)
IntersectionNode = NULL;
pA = pA->next;
pB = pB->next;
}
return IntersectionNode;
}
else
{
pA = headA;
pB = headB;
minus = lengthB - lengthA;
while (minus--)
{
pB = pB->next;
}
while (pA != NULL&&pB != NULL)
{
if (pA->val == pB->val&&IntersectionNode == NULL)
IntersectionNode = pA;
if (pA->val != pB->val)
IntersectionNode = NULL;
pA = pA->next;
pB = pB->next;
}
return IntersectionNode;
}
}
};
LeetCode 160. Intersection of Two Linked Lists
标签:
原文地址:http://www.cnblogs.com/csudanli/p/5746886.html