您的位置:首页 > 编程语言 > Java开发

JAVA: 两个链表的第一个公共结点

2018-03-13 16:25 351 查看
题目:输入两个链表,找出它们的第一个公共结点。
分析:
解法一:利用hashmap的特性。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<>();
while(current1!=null){
hashMap.put(current1,null);
current1=current1.next;
}
while(current2!=null){
if(hashMap.containsKey(current2)){
return current2;
}
current2=current2.next;
}
return null;
}
}解法二:分别遍历两链表得到它们的长度,就能知道那个链表更长。在第二次遍历时,在较长的链表上线走长度差值步,接着再同时出发遍历,直到找到第一个共同结点。
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1=getlistLength(pHead1);
int len2=getlistLength(pHead2);
if(len1<=0||len2<=0||pHead1==null||pHead2==null){
return null;
}
int diff=len1-len2;
ListNode PlistHeadLong=pHead1;
ListNode PlistHeadShort=pHead2;
if(len2>len1){
PlistHeadLong=pHead2;
PlistHeadShort=pHead1;
diff=len2-len1;
}
//长的链表先走diff步
while(diff>0){
PlistHeadLong=PlistHeadLong.next;
diff--;
}

while((PlistHeadLong!=null)&&(PlistHeadShort!=null)&&(PlistHeadLong!=PlistHeadShort)){
PlistHeadLong=PlistHeadLong.next;
PlistHeadShort=PlistHeadShort.next;
}
ListNode firstCommonNode=PlistHeadLong;
return firstCommonNode;

}

public int getlistLength(ListNode pHead){
int length=0;
ListNode pNode=pHead;
while(pHead!=null){
length++;
pHead=pHead.next;
}
return length;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: