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→b3
Begin to intersect at node C1.
Problem Solving Ideas:
The length of the two list is traversed first, then the long minus the short, then the same time, the Java implementation is as follows:
Public ListNode Getintersectionnode (ListNode heada, ListNode headb) { if (heada==null| | headb==null) return null; int lengtha=0,lengthb=0; ListNode tempa=heada,tempb=headb; while (tempa!=null) { tempa=tempa.next; lengtha++; } while (tempb!=null) { tempb=tempb.next; lengthb++; } if (Lengthb>lengtha) { Tempa=heada; heada=headb; Headb=tempa; int Temp=lengtha; LENGTHA=LENGTHB; lengthb=temp; } int LENGTH=LENGTHA-LENGTHB; while (length-->0) heada=heada.next; while (heada!=null) { if (heada==headb) return heada; Heada=heada.next; Headb=headb.next; } return heada; }
Java for Leetcode intersection of Linked Lists