给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。图示两个链表在节点 c1 开始相交:
思路:
1.将两个链表尾部对齐(因为如果两个链表相交,那么从出现交点后的节点应该相同)。要将两个链表尾部对齐就需要知道两个链表的节点数,用两次遍历去做。
2.找出长度较长的链表,链表A长则不变,链表B长则交换链表A、B,即交换头节点与指针,即让链表A始终为那个较长链表。
3.让链表A的指针先走,走长度差个大小,这样curA,curB两个指针同时走的时候,才是尾部对齐。
4.指针相等时即相交。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA=headA;
ListNode* curB=headB;
int lengthA=0,lengthB=0;
while(curA!=NULL){
lengthA++;
curA=curA->next;
}
while(curB!=NULL){
lengthB++;
curB=curB->next;
}
curA=headA;
curB=headB;
if(lengthA<lengthB){
swap(lengthA,lengthB);
//swap(curA,curB);
ListNode*tmp=curA;
curA=curB;
curB=tmp;
}
int length=lengthA-lengthB;
while(length--){
curA=curA->next;
}
while(curA!=NULL){
if(curA==curB)
return curA;
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};