輸入兩個鏈表,找出它們的第一個公共結點。
這道題的解題思路:可能轉進來的鏈表長短不一
1.遍歷鏈表得到鏈表長度。
2.算出兩個鏈表的長度差,定義跑長鏈表的結點,和跑短鏈表的結點
3.同時向後跑,若兩個結點的值相同,則表示已經找到了公共結點,此時跳出循環即可。
如果鏈表的長度分別爲 n 和 m 。
時間複雜度:O(n+m)
空間複雜度:O(1)
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null){
return null;
}
int len1 = linkLen(pHead1);
int len2 = linkLen(pHead2);
int dif = len1 - len2;
ListNode pLong = pHead1,pshort = pHead2;
if(len2 > len1){
pLong = pHead2;
pshort = pHead1;
dif = len2 - len1;
}
for(int i = 0; i < dif; ++i)
pLong = pLong.next;
while(pLong != null && pshort != null && pLong.val != pshort.val){
pLong = pLong.next;
pshort = pshort.next;
}
return pLong;
}
public int linkLen(ListNode pHead){
int i = 0;
while(pHead != null){
pHead = pHead.next;
i++;
}
return ++i;
}
}