两个链表的第一个公共节点
约 788 字大约 3 分钟
题目:
输入两个链表,找出它们的第一个公共结点。链表的节点定义如下:
public class ListNode { int val; ListNode next; }
分析:
第一种:直接法
在第一个链表上顺序遍历每个结点,每遍历到一个结点的时候,在第二个链表上顺序遍历每个结点。如果在第二个链表上有一个结点和第一个链表上的结点一样,说明两个链表在这个结点上重合,于是就找到了它们的公共结点。如果第一个链表的长度为m,第二个链表的长度为n,显然该方法的时间复杂度是O(mn) 。
第二种:使用栈
所以两个有公共结点而部分重舍的链衰,拓扑形状看起来像一个Y(下图所示), 而不可能像X。

经过分析我们发现,如果两个链表有公共结点,那么公共结点出现在两个链表的尾部。如果我们从两个链衰的尾部开始往前比较,最后一个相同的结点就是我们要找的结点。
在上述思路中,我们需要用两个辅助钱。如果链表的长度分别为m 和n,那么空间复杂度是O(m+n)。这种思路的时间复杂度也是O(m+n)。和最开始的蛮力法相比,时间效率得到了提高,相当于是用空间消耗换取了时间效率。第三种:先行法
在上图的两个链表中,我们可以先遍历一次得到它们的长度分别为5 和4, 也就是较长的链表与较短的链表相比多一个结点。第二次先在长的链表上走1 步,到达结点2。接下来分别从结点2 和结点4 出发同时遍历两个结点, 直到找到它们第一个相同的结点6,这就是我们想要的结果。
第三种思路和第二种思路相比,时间复杂度都是O(m+n), 但我们不再需要辅助的栈,因此提高了空间效率。
本题采用第三种方法
代码:
class Solution {
public static ListNode getFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int length1 = getListLength(pHead1);
int length2 = getListLength(pHead2);
ListNode longList = pHead1;
ListNode shortList = pHead2;
int diff = length1 - length2;
if (diff < 0) {
longList = pHead2;
shortList = pHead1;
diff = length2 - length1;
}
// 先在长链上走几步,再同时在两个链表上遍历
for (int i = 0; i < diff; i++) {
longList = longList.next;
}
while (longList != null && shortList != null && longList != shortList) {
longList = longList.next;
shortList = shortList.next;
}
// 返回第一个相同的公共结点,如果没有返回null
return longList;
}
private static int getListLength(ListNode pHead) {
int length = 0;
ListNode pNode = pHead;
while (pNode != null) {
++length;
pNode = pNode.next;
}
return length;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(7);
node1.next = node2;
node2.next = node3;
node3.next = node6;
node6.next = node7;
node4.next = node5;
node5.next = node7;
ListNode commonNode = getFirstCommonNode(node1, node4);
System.out.println(null == commonNode ? null : commonNode.value);
}
}