参照代码随想录思路,先把两个链表右对齐,再向后遍历,遇到相同的元素就返回
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *a=headA;
ListNode *b=headB;
int num = 0;
int i = 0;
int j = 0;
while(a){
i++;
a = a->next;
}
while(b){
j++;
b = b->next;
}
int length = (i>j)?(i-j):(j-i);
a=headA;
b=headB;
int num_a = 0;
int num_b = 0;
int intersectVal = 0;
if(i>j){
while(num_a<length){
num_a++;
a = a->next;
}
while(a){
if(a==b){
return a;
}
else{
num_a++;
num_b++;
a = a->next;
b = b->next;
}
}
}
else{
while(num_b<length){
num_b++;
b = b->next;
}
while(b){
if(a==b){//开始写的a->val==b->val报错,看评论说必须得地址相同
return a;
}
else{
num_a++;
num_b++;
a = a->next;
b = b->next;
}
}
}
return NULL;
}
};
观察随想录代码,发现if(i>j)和else可以合并
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};