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;
}
}解法二:分别遍历两链表得到它们的长度,就能知道那个链表更长。在第二次遍历时,在较长的链表上线走长度差值步,接着再同时出发遍历,直到找到第一个共同结点。
分析:
解法一:利用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; } }
相关文章推荐
- 剑指Offer(Java版):两个链表的第一个公共结点
- 剑指Offer面试题37(Java版):两个链表的第一个公共结点
- (整理)Java实现链表--找到两个链表的第一个公共结点(网易笔试题2016)
- 剑指Offer面试题37(Java版):两个链表的第一个公共结点
- 两个链表的第一个公共结点 java
- 牛客:剑指offer:两个链表的第一个公共结点(Java)
- leetcode解题之160# Intersection of Two Linked Lists Java版 (两个链表的第一个公共结点)
- 剑指offer:两个链表的第一个公共结点(java)
- 剑指Offer:两个链表的第一个公共结点Java
- 两个链表的第一个公共结点(java版)
- 两个链表的第一个公共结点java实现
- 剑指Offer------两个链表的第一个公共结点
- 【36】两个链表的第一个公共结点
- 两链表的第一个公共结点(比较两个链表节点是否相同时比较不了啊,该题尚未完成)
- 【链表】两个链表的第一个公共结点
- 求两个链表的第一个公共结点
- 两个链表的第一个公共结点
- 电话面试:求两个链表的第一个公共结点
- 【剑指Offer学习】【面试题37:两个链表的第一个公共结点】
- 剑指offer--面试题37:两个链表的第一个公共结点