首页 > 其他 > 详细

【剑指offer】链表第一个公共子结点

时间:2018-12-28 19:11:39      阅读:176      评论:0      收藏:0      [点我收藏+]

*思路: 先求得两个链表的长度,然后得到长度差diff,再先遍历长链表diff步后,再同时遍历两个链表并比较对象指针。

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
12       if(pHead1==null||pHead2==null) 
13         {return null;}
14       ListNode temp1 = pHead1;
15       ListNode temp2 = pHead2;
16       int length1=0;
17       int length2=0;
18       while(temp1!=null){
19           length1++;
20           temp1 = temp1.next;
21       }
22       while(temp2!=null){
23           length2++;
24           temp2 = temp2.next;
25       }
26       int diff= Math.abs(length1-length2);
27       if(length1>=length2){
28           for(int i=0; i<diff; i++){
29               pHead1 = pHead1.next;
30           }
31       }else{
32           for(int i=0; i<diff; i++){
33               pHead2 = pHead2.next;
34           }
35       }
36       while(pHead1!=pHead2){
37           pHead1 = pHead1.next;
38           pHead2 = pHead2.next;
39       }
40 
41       return pHead1;
42       
43     }
44 }

 

【剑指offer】链表第一个公共子结点

原文:https://www.cnblogs.com/singular/p/10192277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!