【编程打卡】两个链表的第一个公共节点(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;
}
}