相交链表
找到两个单链表相交的起始节点。
例如:
返回c1节点的值。
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
int s = 0;
int lenA = 0;
int lenB = 0;
struct ListNode* A, * B;
A = headA;
B = headB;
while (A) {
lenA++;
A = A->next;
}
while (B) {
lenB++;
B = B->next;
}
s = abs(lenA - lenB);
//先假定A更长
A = headA;
B = headB;
//万一B更长,那就更改指针指向,这样不影响后边代码更改
if (lenB > lenA) {
A = headB;
B = headA;
}
//更长的先走相差的步数
while (s--) {
A = A->next;
}
while (A && B) {
if (A == B) {
return A;
}
A = A->next;
B = B->next;
}
return NULL;
}