题目描述:
输入两个链表,找出它们的第一个公共结点。
思路解析:
图片来自https://www.cnblogs.com/keedor/p/4469121.html
两个链表有公共节点一定是这个样子的。
- 判断两个节点是否相等;
- 先把两个链表相差的那一段略过;
- 循环:判断是否是空,判断是不是相等,否则就next。
- 另外,判断链表的长度的函数,需要写一下。
代码:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null){
return null;
}
if(pHead1==pHead2){
return pHead1;
}
int length1=getLength(pHead1);
int length2=getLength(pHead2);
if(length1>length2){
for(int i=0;i<length1-length2;i++){
pHead1=pHead1.next;
}
}else{
for(int i=0;i<length2-length1;i++){
pHead2=pHead2.next;
}
}
while(pHead1!=null&&pHead2!=null){
if(pHead1==pHead2){
return pHead1;
}
else{
pHead1=pHead1.next;
pHead2=pHead2.next;
}
}
return null;
}
public static int getLength(ListNode pHead){
int length=0;
ListNode current = pHead;
while(current!=null){
length++;
current = current.next;
}
return length;
}
}