题目描述
输入两个链表,找出它们的第一个公共结点。
源代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1= getlen(pHead1),len2=getlen( pHead2);
if(len1>len2){
pHead1 = getListNode(pHead1,len1-len2);
}else if(len1<len2){
pHead2 = getListNode(pHead2,len2-len1);
}//这样做的目的是为了让两个链表长度相同,再找出公共节点
while(pHead1!=null){
if(pHead1==pHead2) return pHead1;
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
public int getlen(ListNode pHead1){//求链表的长度
int len=0;
while(pHead1!=null){
len++;
pHead1 =pHead1.next;
}
return len;
}
public ListNode getListNode(ListNode pHead1,int step){//将链表的头指针定位到第step个位置
while(step!=0){
pHead1 =pHead1.next;
step--;
}
return pHead1;
}
}
解法二:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.HashMap;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashMap<ListNode,Integer> m=new HashMap<ListNode,Integer>();
while(pHead1!=null){//先将第一个链表中等元素存到HashMap中,
m.put(pHead1,null);
pHead1 = pHead1.next;
}
while(pHead2!=null){//再对第二个链表中的所有节点,如果HashMap中已经包含了以该节点为关键字的元素,则说明是公共节点。
if(m.containsKey(pHead2))
return pHead2;
pHead2 = pHead2.next;
}
return null;
}
}