《劍指offer》系列 兩個連結串列的第一個公共結點(Java)
阿新 • • 發佈:2018-11-25
連結
題目描述
輸入兩個連結串列,找出它們的第一個公共結點。
思路
倆個連結串列存在公共結點,意味著第一個公共結點之後的都是相同的,就是說,兩個連結串列的尾巴是相同的,我們可以分別算出兩個連結串列的長度之差lenDif ,然後遍歷長連結串列到lenDif的位置,再一起遍歷兩個連結串列,找到第一個相同的即可。
程式碼
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int len1 = getLen(pHead1); int len2 = getLen(pHead2); int lenDif = 0; ListNode pLong = null; ListNode pShort = null; if(len1 >= len2){ lenDif = len1-len2; pLong = pHead1; pShort = pHead2; } else { lenDif = len2-len1; pLong = pHead2; pShort = pHead1; } for(int i = 0; i < lenDif; i++){ pLong = pLong.next; } while(pLong != null && pShort != null && pLong != pShort){ pLong = pLong.next; pShort = pShort.next; } ListNode pFirstCommon = pLong; return pFirstCommon; } public int getLen(ListNode pHead){ int len = 0; ListNode pNode = pHead; while(pNode!=null){ len++; pNode = pNode.next; } return len; } }