相交链表对应力扣160题。因为c++语法还在学习中,还没有学到哈希表,看题解是用哈希表写的,等后续学了哈希表再回来重新写过用哈希表的方法。我这里直接用的比较容易想到的,计算链表长度差,然后长短链表对齐,相交节点相同就行,写的比较冗余。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//计算两个链表的各自长度
int count_A=0,count_B=0;
ListNode *tempA=headA;
ListNode *tempB=headB;
while(tempA){
count_A++;
tempA=tempA->next;
}
tempA=headA;
while(tempB){
count_B++;
tempB=tempB->next;
}
tempB=headB;
//计算两个链表的长度差,相交节点以后一定一样长,移动长链表对齐于短链表
int gas;
if(count_A>=count_B){
gas=count_A-count_B;
while(gas>0){
tempA=tempA->next;
gas--;
}
}
else{
gas=count_B-count_A;
while(gas>0){
tempB=tempB->next;
gas--;
}
}
//进行遍历判断相同节点
while(tempB){
if(tempB == tempA) return tempA;
else{
tempA=tempA->next;
tempB=tempB->next;
}
}
return NULL;
}
};