36.两个链表的第一个公共结点
输入两个链表,找出它们的第一个公共结点
方法1:开始遍历两遍链表获取两个表的长度,比较长度让长的一个先走差值个步长,再两个一起走。(快慢指针思想,也是链表问题的一般性思路)
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1=pHead1;//链表1
ListNode p2=pHead2;//链表2
if(p1==null||p2==null) return null;
int len1=getlen(p1);
int len2=getlen(p2);
//链表的长度差
//如果链表1的长度大于链表2的长度
if(len1>=len2){
int len=len1-len2;
//先遍历链表1,遍历的长度就是两链表的长度差
while(len>0){
p1=p1.next;
len--;
}
}
//如果链表2的长度大于链表1的长度
else if(len1<len2){
int len=len2-len1;
//先遍历链表2,遍历的长度就是两链表的长度差
while(len>0){
p2=p2.next;
len--;
}
}
//开始起头并进,直到找到第一个公共结点
while(p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p1;
}
//求指定链表的长度
public static int getlen(ListNode pHead){
int len=0;
ListNode p=pHead;
while(p!=null){
len++;
p=p.next;
}
return len;
}
}
方法2:运用hashmap的特性
import java.util.HashMap;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1=pHead1;
ListNode p2=pHead2;
HashMap<ListNode,Integer> map=new HashMap<ListNode,Integer>();
while(p1!=null){
map.put(p1,null);
p1=p1.next;
}
while(p2!=null){
if(map.containsKey(p2))
return p2;
p2=p2.next;
}
return null;
}
}