【劍指offer】連結串列第一個公共子結點
阿新 • • 發佈:2018-12-28
*思路: 先求得兩個連結串列的長度,然後得到長度差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 }