两个链表的第一个公共结点
描述
输入两个链表,找出它们的第一个公共结点。
代码 (Java)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int length1 = GetListLength(pHead1);
int length2 = GetListLength(pHead2);
int lengthDif = length1 - length2;
ListNode pLongList = pHead1;
ListNode pShortList = pHead2;
if (length2 > length1) {
pLongList = pHead2;
pShortList = pHead1;
lengthDif = length2 - length1;
}
for (int i = 0; i < lengthDif; ++i) {
pLongList = pLongList.next;
}
while ((pLongList != null) && (pShortList != null) && (pLongList != pShortList)) {
pLongList = pLongList.next;
pShortList = pShortList.next;
}
return pLongList;
}
public int GetListLength(ListNode node) {
int len = 0;
while (node != null) {
len++;
node = node.next;
}
return len;
}
}
思路
- 代码的时间复杂度是O(m+n),两个链表如果有公共点,那么它们会组成一个Y字型,因为是单向链表。分别遍历两条链表得到长度,即可得到长度差,然后让长链先走长度差的节点数,这样两条链就能同时到达公共节点了;
- 还有一种思路是用两个辅助栈,分别遍历两条链,把节点分别入栈,然后从后往前出栈,知道找到最后一个相同的节点,则其就是第一个公共节点,时间复杂度也是O(m+n),只不过也需要O(m+n)的空间。