1. 程式人生 > >【劍指offer】鏈表第一個公共子結點

【劍指offer】鏈表第一個公共子結點

stc 一個 fir listnode 比較 nod fin first 第一個

*思路: 先求得兩個鏈表的長度,然後得到長度差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】鏈表第一個公共子結點