題目描述:編寫一個程式,找到兩個單連結清單相交的起始節點。

連結清單A和連結清單B在節點C1處相交,則傳回c1節點。
解題思路:先求出兩個連結清單的長度,讓pl指向長連結清單,ps指向短連結清單。在讓pl先走它倆的內插補點步,然後在讓pl和ps同時走,如果pl=ps,則傳回pl,否則傳回null。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
//求兩個連結清單的長度
int headALength=0;
int headBLength=0;
ListNode cur=headA;
while(cur!=null){
headALength++;
cur=cur.next;
}
ListNode cur1=headB;
while(cur1!=null){
headBLength++;
cur1=cur1.next;
}
int a=0;
ListNode pL=null; //pL指向最長的單連結清單
ListNode pS=null;//pS指向最短的單連結清單
if(headALength>=headBLength){
pL=headA;
pS=headB;
a=headALength-headBLength;
}else{
pL=headB;
pS=headA;
a=headBLength-headALength;
}
//長的單連結清單走它倆的內插補點步
for(int i=0;i<a;i++){
pL=pL.next;
}
//然後pL和pS同時走,看它倆是否相等
while(pL!=null||pS!=null){
if(pL==pS){
return pL;
}
pL=pL.next;
pS=pS.next;
}
return null; //不相等傳回null;
}
}