题目:求两个单链表的第一个公共子节点。
思路:我们可以先遍历两个单链表得到长度,然后求得两个链表长度的差值,然后让长的那个链表先走到差值长度位置,然后两个链表再同时遍历,直到找到第一个公共节点。
struct ListNode {
int value;
ListNode *next;
};
int getListLength(ListNode *head){
if(head == NULL)
return 0;
ListNode *p = head;
int len = 0;
while(p != NULL){
len++;
p = p->next;'
}
return len;
}
ListNode *FindFirstCommonNode(ListNode *head1,ListNode *head2){
int len1 = getListLength(head1);
int len2 = getListLength(head2);
int diff = len1 - len2;
ListNode *longList = head1;
ListNode *shortList = head2;
if(len2 > len1){
longList = head2;
shortList = head1;
diff = len2 - len1;
}
for(int i = 0;i < diff;i++){
longList = longList->next;
}
while(longList && shortList && longList != shortList){
longList = longList->next;
shortList = shortList->next;
}
ListNode *firstcommonnode = NULL;
if(longList == shortList)
firstcommonnode = longList;
return firstcommonnode;
}