题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
解题思路
首先需要明白公共节点就是同一个节点,而不是说节点值一样
如果两个节点长度一样,则直接遍历链表,比较是否相等即可
主要针对两个链表长度不一致的情况
解法一:公共节点之后的部分肯定是重合的,那么公共节点之后的部分肯定是长度相同的
那我们需要先计算出两个链表的长度差,让较长的链表先走过长度差的位置,之后哦才进行一一比较
解法二:将两个链表变成a+b,b+a的形式。这样两个链表长度就一样了,之后也就可以一一进行比较了
两种解法最终的原理都是为了将两个链表的尾端对齐,然后进行一一比较
解法一代码
/*
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;
// 求两链表的长度
int count1 = 0;
ListNode p1 = pHead1;
while(p1 != null) {
p1 = p1.next;
count1++;
}
int count2 = 0;
ListNode p2 = pHead2;
while(p2 != null) {
p2 = p2.next;
count2++;
}
// 将长链表的指针移动到和短链表相同长度的位置
int flag = count1-count2;
if(flag > 0) {
while(flag > 0) {
pHead1 = pHead1.next;
flag--;
}
while(pHead1 != pHead2) {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
else {
flag = -flag;
while(flag > 0) {
pHead2 = pHead2.next;
flag--;
}
while(pHead1 != pHead2) {
pHead1 = pHead1.next;
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) {
if(pHead1 == null || pHead2 == null)return null;
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while(p1!=p2){
p1 = p1.next;
p2 = p2.next;
if(p1 != p2){
if(p1 == null)p1 = pHead2;
if(p2 == null)p2 = pHead1;
}
}
return p1;
}
}
京公网安备 11010502036488号