题解 | #合并两个排序的链表#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
此法不行,求解 package com.yzc.offer.JZ52; import java.util.ArrayList; import java.util.HashMap; /** * @author YZC * @Date 2021/12/3/11:30 */ public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } @Override public String toString() { return "ListNode{" + "val=" + val + ", next=" + next + '}'; } } class Solution { 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); ListNode node8 = new ListNode(8); node1.next = node2; node2.next = node3; node3.next = node6; node6.next = node7; node4.next = node5; node5.next = node6; node6.next = node7; node7.next = node8; System.out.println(FindFirstCommonNode(node1, node4)); } public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if (pHead1 == null || pHead2 == null) { return null; } ArrayList<Integer> list = new ArrayList<>(); while (pHead1 != null) { list.add(pHead1.val); pHead1 = pHead1.next; } ArrayList<Integer> list2 = new ArrayList<>(); while (pHead2 != null) { // list.add(pHead2.val); if (list.contains(pHead2.val)) { list2.add(pHead2.val); return pHead2; } pHead2 = pHead2.next; } if (list2.size() == 0) { return null; } Integer integer = list2.get(0); System.out.println(list2); ListNode newNode = new ListNode(integer); // ListNode result = newNode; // // for (int i = 1; i < list2.size(); i++) { // System.out.println(list2.get(i)); // ListNode listNode = new ListNode(list2.get(i)); // newNode.next = listNode; // newNode = newNode.next; // } // return newNode; return null; } }
测试成功:放入map中
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;