劍指offer之兩個連結串列的第一個公共點(Java實現)
阿新 • • 發佈:2018-12-11
兩個連結串列的第一個公共點
輸入兩個連結串列,找出它們的第一個公共結點
思路:我們先遍歷找到兩個連結串列的長度m和n,
如果m大,m比n大多少,比如說k,那麼先讓m先走k步,然後n和m再一起走。
程式碼:
/* public class ListNode{ int val; ListNode.next = null; ListNode(int val){ this.val = val; } } */ public class Solutin{ public ListNode FindFirstCommonNode(ListNode pHead1,ListNode pHead2){ ListNode p1 = pHead1; ListNode p2 = pHead2; int list1_len = 0; int list2_len = 0; //求list1和list2的長度 while(p1 != null ){ list1_len ++; p1 = p1.next; } while (p2 != null) { list2_len ++; p2 = p2.next; } //求出長度差 int nLength = list1_len - list2_len; ListNode pLong = pHead1; ListNode pShort = pHead2; if (list1_len < list2_len) { pLong = pHead2; pShort = pHead1; nLength = list2_len - list1_len; } //長的先走nLength步 for (int i =0;i< nLength;i++) { pLong = pLong.next; } //此時長度一致,一起向前走,並判斷他們的值是否相等 while (pLong != null && pShort != null && pLong != pShort) { pLong = pLong.next; pShort = pShort.next; } return pLong; } }
測試結果: