leetcode 160. 相交链表

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:

 

 

 

在节点 c1 开始相交。

 1 public class Solution {
 2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 3         ListNode iteratorA = headA;
 4         ListNode iteratorB = headB;
 5         ListNode intersect = null;
 6         int lenA = 0;
 7         int lenB = 0;
 8         int num = 0;
 9         while(iteratorA!=null||iteratorB!=null){
10             if(iteratorA!=null){
11                 lenA++;
12                 iteratorA=iteratorA.next;
13             }
14             if(iteratorB!=null){
15                 lenB++;
16                 iteratorB=iteratorB.next;
17             }
18         }
19         while(headA!=null&&headB!=null){
20             if(lenA>lenB){
21                 headA=headA.next;
22                 lenA--;
23             }else if(lenB>lenA){
24                 headB=headB.next;
25                 lenB--;
26             }else{
27                 if(headA==headB){
28                     intersect=headA;
29                     break;
30                 }
31                 headA=headA.next;
32                 headB=headB.next;
33             }
34         }
35         return intersect;
36     }
37 }

 

 

posted on 2019-12-02 09:26  forever_time  阅读(125)  评论(0编辑  收藏  举报