题目描述:编写一个程序,找到两个单链表相交的起始节点。
链表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;
}
}