题目描述
输入两个链表,找出它们的第一个公共结点。
样例
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
输入A,B,输出c1
思路分析
方法一:找到长链表,先行走数步,走到长度相等时,再开始比较
方法二:双指针法,每个指针一次扫描两链表各一次,找到公共节点,第二种写法虽然很短,但很优雅,值得深入琢磨
两链表长度相同有公共结点,第一次就遍历到;没有公共结点,走到尾部NULL相遇,返回NULL
长度不同有公共结点,第一遍差值就出来了,第二遍一起到公共结点;没有公共,一起到结尾NULL。
代码及结果
方法一:
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
int l1 = length(pHead1);
int l2 = length(pHead2);
if (l1 > l2) {
int len = l1 - l2;
while (len > 0) {
cur1 = cur1.next;
len--;
}
}
else if (l1 < l2) {
int len = l2 - l1;
while (len > 0) {
cur2 = cur2.next;
len--;
}
}
while (cur1 != cur2) {
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur2;
}
public int length(ListNode phead){
int length = 0;
ListNode node = phead;
while (node != null) {
length++;
node = node.next;
}
return length;
}

方法二:
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode cur1 = pHead1;
ListNode cur2 = pHead2;
while (cur1 != cur2) {
cur1 = cur1==null ? pHead2 : cur1.next;
cur2 = cur2==null ? pHead1 : cur2.next;
}
return cur2;
}

本文探讨了两个链表寻找第一个公共结点的问题,提出了两种有效的方法:通过测量链表长度差并同步移动指针的方法一,以及更简洁优雅的双指针法。通过实例分析,展示了算法的实现细节。
774

被折叠的 条评论
为什么被折叠?



