【編程打卡】兩個鏈表的第一個公共節點(Java實現)
題目來源
劍指offer第36題
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
題目描述
輸入兩個鏈表,找出它們的第一個公共結點。
題目代碼
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
Set<ListNode>set=new HashSet<>();
while(pHead1!=null){
set.add(pHead1);
pHead1=pHead1.next;
}
while(pHead2!=null){
if(set.contains(pHead2))
return pHead2;
pHead2=pHead2.next;
}
return pHead2;
}
}
/*
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 d=null;
int i=0;
ListNode l1=pHead1;
ListNode l2=pHead2;
int count1=countlength(pHead1);
int count2=countlength(pHead2);
int x;
if(count1<count2){
x=count2-count1;
while(x-->0){
pHead2=pHead2.next;
}
}else
{
x=count1-count2;
while(x-->0){
pHead1=pHead1.next;
}
}
while(pHead1!=null&&pHead2!=null){
if(pHead1==pHead2)
return pHead1;
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return d;
}
int countlength(ListNode pHead1){
int count1=0;
while(pHead1!=null){
pHead1=pHead1.next;
count1++;
}
return count1;
}
}