题目描述
输入两个链表,找出它们的第一个公共结点。
链表定义如下:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
题中的公共节点的意思是val相同,next节点也相同。
评论区有种解法很巧妙:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode curr1 = pHead1;
ListNode curr2 = pHead2;
while(curr1 != curr2){
curr1 = (curr1 == null ? pHead2 : curr1.next);
curr2 = (curr2 == null ? pHead1 : curr2.next);
}
return curr1;
}
}
但是由于没有看到对这个答案合适的解析,大多数停留在感叹巧妙的阶段。所以写下这篇博客分享一下我的理解:
可以将这种方法看做是两个链表的拼接,两个链表分别为list1+list2,list2+list1。
其中划横线的部分表示公共节点及后续部分。
可以看到在有公共部分的情况下,遍历至list1.length+list2.length之前时一定能找到公共部分。
如果没有公共部分则在遍历完成后一同返回null退出循环。
因此评论中所说的复杂度不稳定是不正确的,如图复杂度是O(n)。