题意
求两个链表的交点
思路
思路一:求出两个链表的长度差,然后将较长的一个偏移长度差的长度,然后求交点
思路二:类似于求链表是否存在环,设定两个指针,如果一个指针走到底了,那么从另一个链表的头节点开始继续,直到两个指针相等.
代码
思路一:
/**
* 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) {
if(headA == NULL || headB == NULL){
return NULL;
}
ListNode *tempA = headA;
int lenA = 0;
ListNode *tempB = headB;
int lenB = 0;
while(tempA != NULL){
tempA = tempA->next;
lenA++;
}
while(tempB != NULL){
tempB = tempB->next;
lenB++;
}
int num = lenA - lenB;
tempA = headA;
tempB = headB;
if(num > 0) {
while(num){
tempA = tempA->next;
num--;
}
} else {
num = -num;
while(num){
tempB = tempB->next;
num--;
}
}
while(tempA != tempB){
tempA = tempA->next;
tempB = tempB->next;
}
return tempA;
}
};
思路二:
/**
* 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) {
if(headA == NULL || headB == NULL){
return NULL;
}
ListNode *tempA = headA;
ListNode *tempB = headB;
while(tempA != tempB){
if(tempA == NULL) {
tempA = headB;
} else {
tempA = tempA->next;
}
if(tempB == NULL) {
tempB = headA;
} else {
tempB = tempB->next;
}
}
return tempA;
}
};