题目描述
输入两个链表,找出它们的第一个公共结点。
1 import java.util.HashSet; 2 import java.util.Set; 3 4 /** 5 * 6 * @author gentleKay 7 * 题目描述 8 * 输入两个链表,找出它们的第一个公共结点。 9 */ 10 11 public class Main35 { 12 public static void main(String[] args) { 13 ListNode head1 = new ListNode(1); 14 head1.next = new ListNode(2); 15 head1.next.next = new ListNode(3); 16 head1.next.next.next = new ListNode(6); 17 head1.next.next.next.next = new ListNode(7); 18 19 ListNode head2 = new ListNode(4); 20 head2.next = new ListNode(5); 21 head2.next.next = new ListNode(6); 22 head2.next.next.next = new ListNode(7); 23 24 System.out.println(Main35.FindFirstCommonNode(head1, head2)); 25 26 // ListNode root = Main35.FindFirstCommonNode(head1, head2); 27 // System.out.println(root.val); 28 } 29 30 public static class ListNode { 31 int val; 32 ListNode next = null; 33 34 ListNode(int val) { 35 this.val = val; 36 } 37 } 38 39 public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { 40 41 ListNode node1 = pHead1; 42 ListNode node2 = pHead2; 43 44 Set<ListNode> hashSet = new HashSet<>(); 45 while (node1 != null) { 46 hashSet.add(node1); 47 node1 = node1.next; 48 } 49 while (node2 != null) { 50 if (hashSet.contains(node2)) { 51 return node2; 52 } 53 node2 = node2.next; 54 } 55 return null; 56 } 57 }