两个链表的第一个公共结点
两个链表第一个公共结点后都是公共结点,呈Y型,非X型。也就是说两个链表在第一个节点重合之后不会再分开了
方法一:利用两个链表的长度差
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
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 length1=getLength(p1);
int length2=getLength(p2);
//求得两链表的长度差,使其较长的链表当前结点遍历一个长度差
if(length1>=length2){
int len=length1-length2;
while(len>0){
p1=p1.next;
len--;
}
}
else {
int len=length2-length1;
while(len>0){
p2=p2.next;
len--;
}
}
//开始齐头并进,直到找到第一个公共结点
while(p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p1;
}
//求链表长度
public static int getLength(ListNode pHead){
int length=0;
ListNode current=pHead;
while(current!=null){
length++;
current=current.next;
}
return length;
}
}
方法二:利用HashMap中containsKey()函数,调用containsKey方法查询是否包含指定的键名。
import java.util.HashMap;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode current1=pHead1;
ListNode current2=pHead2;
HashMap<ListNode,Integer> hashMap=new HashMap<ListNode,Integer>();
while(current1!=null){
hashMap.put(current1,null);
current1=current1.next;
}
while(current2!=null){
if(hashMap.containsKey(current2)){
return current2;
}
current2=current2.next;
}
return null;
}
}