首先将两个链表进行"对齐".(两个链表相交也就是说,从相交的结点开始,后面两个链表内容相同).
思路
首先通过链表遍历,求出两个链表的长度,得到其差值.
创建两个指针分别指向这两个链表的头位置.
然后对较长的链表开始从头遍历差值部分,接下来让两个指针一起向前走,若相遇则得到两链表相交结点,否则两链表不相交.
SListNode *getIntersectionNode(Slist *listA, SList * listB)
{
int lenA = 0;
int lenB = 0;
SListNode *cur;
SListNode * headlong = listA;
SListNode * headshort = listB;
int gap;
int i;
for (cur = listA->_head; cur; cur = cur->_next)
{
lenA++;
}
for (cur = listB->_head; cur; cur = cur->_next)
{
lenB++;
}
gap = lenA - lenB;
if (gap<0)
{
gap *= -1;
headlong = listB->_head;
headshort = listA->_head;
}
for (i = 0; i < gap; i++)
{
headlong = headlong->_next;
}
for (; headlong; headlong = headlong->_next, headshort = headshort->_next)
{
if (headlong==headshort)
{
return headlong;
}
}
return NULL;
}