题目描述
输入两个链表,找出它们的第一个公共结点。
解题思路如下:
我解题的思路:
1. 利用Map保存每个节点的值,和对应的ListNode。先遍历我们的第一个链表,然后再让第二个链表在map中去寻找值,是否能寻找得到呢?
package JianzhiOffer;
import java.util.HashMap;
import java.util.Map;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Slution34 {
/** * 利用Map做 * * @param pHead1 * @param pHead2 * @return */
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
Map<ListNode, Integer> map = new HashMap<ListNode, Integer>();
while (pHead1 != null) {
map.put(pHead1, pHead1.val);
pHead1 = pHead1.next;
}
while (pHead2 != null) {
if (map.containsValue(pHead2.val)) {
return pHead2;
}
pHead2 = pHead2.next;
}
return null;
}
}
声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。