力扣:面试题 02.07. 链表相交
题目:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
思路:
我们求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置。将两个链表从末尾出对齐,从对齐开始处,依次比较节点从而找出交点。
看while循环只需要看头就可以(因为通过循环体可从开始推到结束)如:
ListNode* curA = headA;
int lenA = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
curA 从 headA 到 NULL,lenA从0到 对应位置的长度。因为是求长度又因为lenA是从0开始的,所以curA最终是到NULL。
curA = headA;
int gap = lenA - lenB;
while (gap--) {
curA = curA->next;
}
gap从 lenA-lenB 到0,curA也将会从headA到目标位置。
此时 lenA,lenB 有三种情况,那么写代码就相当于两种情况(==归纳为其中一中)繁琐,通过swap设定lenA为长的,将两种情况转换成一种形式。
int length = lenA - lenB;
while(length--){
nodeA = nodeA->next;
}
length从0到两者之差(此时这个两者之差代表的位置就是相交节点的位置),因此node是从headA到相交节点的位置。
总体代码:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA = 0, lenB = 0;
ListNode *nodeA = headA;
ListNode *nodeB = headB;
while(nodeA != NULL){
nodeA = nodeA ->next;
lenA ++;
}
while(nodeB != NULL){
nodeB = nodeB->next;
lenB++;
}
nodeA = headA;
nodeB = headB;
if(lenB > lenA){
swap(lenA,lenB);
swap(nodeA,nodeB);
}
int length = lenA - lenB;
while(length--){
nodeA = nodeA->next;
}
while(nodeA != NULL){
if(nodeA == nodeB){
return nodeA;
}
nodeA = nodeA->next;
nodeB = nodeB->next;
}
return NULL;
}
};