1. 题目描述
输入两个链表,找出它们的第一个公共节点。
2. 思路
(1)比较两个链表的长度,让长的先走,直到两个链表的长度相等;
(2)两个链表同时一起走,比较两个链表是否相等。如果相等,则返回结点。否则当遍历完时,返回null。
3. 代码
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null)
return null;
ListNode tempA = headA;
ListNode tempB = headB;
int numA = 0;
int numB = 0;
//链表A长度
while(tempA!=null){
numA++;
tempA = tempA.next;
}
//链表B长度
while(tempB!=null){
numB++;
tempB = tempB.next;
}
tempA = headA;
tempB = headB;
//A长,让A先走
if(numA>numB){
for(int i=0;i<numA-numB;i++){
tempA = tempA.next;
}
}else{//B长,让B先找。长度相等时,不操作
for(int i=0;i<numB-numA;i++){
tempB = tempB.next;
}
}
//同时遍历A和B,找到第一个公共结点则返回
while(tempA!=null && tempB!=null){
if(tempA == tempB)
return tempA;
tempA = tempA.next;
tempB = tempB.next;
}
return null;//没有公共结点
}
}