题目描述
编写一个程序,找到两个单链表相交的起始节点。
样例
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *a, ListNode *b) {
if(a == NULL || b == NULL) return NULL;
ListNode *t1 = a, *t2 = b;
while(t1 != t2)
{
if(t1 != NULL)
t1 = t1->next;
else t1 = b;
if(t2 != NULL)
t2 = t2->next;
else t2 = a;
}
return t1;
}
};