LeetCode 面试题 02.07.链表相交
思路
题目的本意其实就是求两个链表相交处结点的指针,并返回该结点指针
步骤:
Step1.分别用两个指针curA、curB指向两个链表A、B的头结点
Step2.求出链表A与链表B的链表长度
Step3.实现两个链表末尾对齐,并且让curA与curB在同一起始结点上
Step4.循环遍历两个链表,遇到相同的结点则直接返回
代码
class Solution {
public:
int getListLength(ListNode *cur){
int len = 0;
while(cur != nullptr){
len++;
cur = cur->next;
}
return len;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// step1.分别用两个指针curA、curB指向两个链表A、B的头结点
ListNode *curA = headA;
ListNode *curB = headB;
// step2.求出链表A与链表B的链表长度
int lenA = getListLength(curA);
int lenB = getListLength(curB);
// curA = headA;
// curB = headB;
// step3.实现两个链表末尾对齐,并且让curA与curB在同一起始结点上
if(lenA < lenB){
swap(curA, curB);
swap(lenA, lenB);
}
int gap = lenA - lenB;
while(gap--){
curA = curA->next;
}
// step4.循环遍历两个链表,遇到相同的结点则直接返回
while(curA != nullptr){
if(curA == curB){
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};