两个链表的第一个公共结点
题目描述:
输入两个链表,找出它们的第一个公共结点
解题思路:
//解法一:运用HasnMap的特性
import java.util.HashMap;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode current1 = pHead1;
ListNode current2 = pHead2;
HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
while (current1 != null) {
hashMap.put(current1, null);
current1 = current1.next;
}
while (current2 != null) {
if (hashMap.containsKey(current2))
return current2;
current2 = current2.next;
}
return null;
}
}
//解法二:先遍历找到两个链表的长度m和n,如果m大,m比n大多少,比如说k,那么先让m先走k步,然后n和m再一起走
public class Solution {
//PHead1链表1的头指针
//pHead2链表2的头指针
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
int list_1_len = 0;
int list_2_len = 0;
// 分别计算两个链表的长度
while (p1 != null) {
list_1_len++;
p1 = p1.next;
}
while (p2 != null) {
list_2_len++;
p2 = p2.next;
}
// 长度差
int nLength = list_1_len - list_2_len;
ListNode pLong = pHead1;
ListNode pShort = pHead2;
//如果list_1_len<list_2_len
if (list_1_len < list_2_len) {
pLong = pHead2;
pShort = pHead1;
nLength = list_2_len - list_1_len;
}
// 长的先走nLength步
for (int i = 0; i < nLength; i++) {
pLong = pLong.next;
}
// 此时长度相等,一起向前走,并判断他们的值是否相等
while (pLong != null && pShort != null && pLong != pShort) {
pLong = pLong.next;
pShort = pShort.next;
}
return pLong;
}
}