Intersection of Two Linked Lists

基本思想:

首先统计两个链表的长度,并且在循环的过程中,看是否最终是会聚到同一个位节点,若是,则表示两个表有交汇,若否,这返回NULL

之后,对长表进行修剪,剪去多余的表头部分,之后两表并列循环向后查找,找到相同项即是交汇节点。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         ListNode * tail1;
13         ListNode * tail2;
14         ListNode * head1=headA;
15         ListNode * head2=headB;
16         if(headA==headB)
17             return headA;
18         int len1=0;
19         int len2=0;
20         while(head1!=NULL)
21         {
22             len1++;
23             tail1=head1;
24             head1=head1->next;
25         }
26         while(head2!=NULL)
27         {
28             len2++;
29             tail2=head2;
30             head2=head2->next;
31         }
32         if(tail1!=tail2)
33         {
34             return NULL;
35         }
36         /* 找到长链表然后 剪掉多的部分  */
37         head2=headB;
38         head1=headA;
39         if(len1>=len2)
40         {
41             int cha=len1-len2;
42             while(cha!=0)
43             {
44                 head1=head1->next;
45                 cha--;
46             }
47         }
48         else
49         {
50  
51             int cha=len2-len1;
52             while(cha!=0)
53             {
54                 head2=head2->next;
55                 cha--;
56             }
57         }
58         while(true)
59         {
60             if(head1==head2)
61                 return head1;
62             head1=head1->next;
63             head2=head2->next;
64         }
65     
66     }
67 };
原文地址:https://www.cnblogs.com/aguai1992/p/4620309.html