Title Link: intersection-of-two-linked-lists
/** * Write A program to find the node at which the intersection of the singly linked lists begins. For example, the following, linked lists:a: A1→a2 c1→c2→c3 B:b1→b2→b3begin to intersect at node C1. Notes:if The linked lists has no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there is no cycles anywhere in the entire linked structure. Your code should preferably run in O (n) time and use only O (1) memory. * */public class Intersectionoftwolinkedlists {public class ListNode {int val; ListNode Next; ListNode (int x) {val = x; next = null; }}//42/42 test Cases passed.//status:accepted//runtime:327 ms//submitted:3 minutes ago//Time complexity O (m+n) space complexity O (1)///problem-solving ideas://1. The number of nodes that count the two linked lists is first traversed separately. 2. Then traverse again, this time the list of the larger number of nodes to go first | two-node difference | step//3. At the same time, determine whether the nodes are equal public ListNodeGetintersectionnode (ListNode Heada, ListNode headb) {int NumA = 0;//a List of nodes int numB = number of nodes 0;//b list listn Ode CurA = Heada; ListNode CurB = headb; while (CurA! = null) {Numa++;cura = Cura.next;} while (CurB! = null) {numb++;curb = Curb.next;} CurA = Heada;curb = Headb;while (NumA < NumB) {CurB = Curb.next;numb--;} while (NumA > NumB) {curA = Cura.next;numa--;} while (CurA! = CurB) {CurA = Cura.next;curb = Curb.next;} return CurA; }public static void Main (string[] args) {//TODO auto-generated method stub}}
[Leetcode 160] Intersection of Linked Lists