详情请参照B站:正月点灯笼视频讲解。
#include<cstdio>
#include<cmath>
struct node{
int value;
struct node* next;
};
int get_list_length(node* list){
node* p = list;
int cnt=0;
while(p != NULL){
p = p->next;
cnt++;
}
return cnt;
}
node* find_common_node(node* list1, node* list2){
int length1 = get_list_length(list1);
int length2 = get_list_length(list2);
node* long_list = list1;
node* short_list = list2;
int offset = abs(length1 - length2);
if(length2 > length1){
long_list = list2;
short_list = list1;
}
node* p1 = long_list, * p2 = short_list;
for(int i=0; i<offset; i++){
p1 = p1->next;
}
while(p1!=NULL){
if(p1 == p2){
return p1;
}
p1 = p1->next;
p2 = p2->next;
}
return NULL;
}
int main(){
node n1,n2,n3,n4,n5,n6,n7;
n1.value = 1;
n2.value = 2;
n3.value = 3;
n4.value = 4;
n5.value = 5;
n6.value = 6;
n7.value = 7;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = NULL;
n7.next = &n4;
node* list1 = &n1;
node* list2 = &n7;
node* p = find_common_node(list1, list2);
printf("%d\n",p->value);
}
Leetcode160
/** * 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* list1=headA,*list2=headB;
int len1=0,len2=0;
while(list1){
len1++;
list1=list1->next;
}
while(list2){
len2++;
list2=list2->next;
}
ListNode* long_list=headA,*short_list=headB;
if(len2 > len1){
long_list=headB;
short_list=headA;
}
int offset=abs(len1 - len2);
for(int i=0;i<offset;i++){
long_list=long_list->next;
}
while(long_list&&short_list&&long_list!=short_list){
long_list=long_list->next;
short_list=short_list->next;
}
return long_list==short_list?long_list:0;
}
};
其他风格
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
int getlength(ListNode* head){
int r=0;
while(head){
++r;
head=head->next;
}
return r;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* list1=headA,*list2=headB;
int lenA=getlength(headA),lenB=getlength(headB);
if(lenA > lenB){
for(int i=0;i<lenA-lenB;i++){
headA=headA->next;
}
}else{
for(int i=0;i<lenB-lenA;i++){
headB=headB->next;
}
}
while(headA&&headB&&headA!=headB){
headA=headA->next;
headB=headB->next;
}
return headA==headB? headA :0;
}
};