Topic describes

Enter two lists to find their first common node. // Enter two linked lists to find their first common node. (Note that since the incoming data is a linked list, the error test data prompt is displayed in a different way to ensure that the incoming data is correct)Copy the code

Answer key

If the total length of A list is A(private chain)+P(public chain), then we must have A+P+B = B+P+A. // let p1 and P2 go from A to B, and p1 and P2 go from A to B, and P2 and P2 go from B to B, and p2 and P2 go from B to B. // Run time: 12ms, over 95.24% code submitted in Java 9816 KB, Public Class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode p1 = pHead1; ListNode p2 = pHead2; while (p1 ! = p2) { if (p1 ! = null) p1 = p1.next; else p1 = pHead2; if (p2 ! = null) p2 = p2.next; else p2 = pHead1; } return p1; }} * * * * * * * * * * * * * * * * * * * * 9988 KB, Public Class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode p1 = pHead1; ListNode p2 = pHead2; while (p1 ! = p2) { p1 = (p1 == null) ? pHead2 : p1.next; p2 = (p2 == null) ? pHead1 : p2.next; } return p1; }} // memory consumption beat 100.00% in all Java commits: Public Class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode p1 = headA, p2 = headB; while (p1 ! = p2) { p1 = (p1 == null) ? headB : p1.next; p2 = (p2 == null) ? headA : p2.next; } return p1; }}Copy the code