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.
Or think about it, put the listnode in the stack, and then one pop out, until it's different, then the previous point is the merge point.
On the internet did not find anything else to write this question, it seems I was the first wave to write this question ~
Public ListNode Getintersectionnode (ListNode heada, ListNode headb) {if (heada==null| | Headb==null) return null; Stack<listnode>stacka = new stack<listnode> (); stack<listnode>stackb = new stack<listnode> (); STACK<LISTNODE>STACKC = new stack<listnode> ();//For the final output of the merge ListNode listnode a = Heada; ListNode B = headb; int I=1,j=1;while (a.next!=null) {Stacka.push (a); a=a.next;i++;} Stacka.push (a);//end, push all listnode into Stacka, as below Stackbwhile (b.next!=null) {Stackb.push (b); b=b.next;j++;} Stackb.push (b);//Ibid. if (a.val!=b.val) return Null;while (i>0&&j>0) {ListNode bottoma=stacka.pop (); ListNode Bottomb=stackb.pop (); if (bottomb.val==bottoma.val)//If A and B stack pops out, deposit in C, not the same then output {Stackc.push ( Bottoma); i--;j--;} Else{return Stackc.pop ();}} if (i==0) return heada;//If one is already in the head, then the head is the merge point else return headb; }
"Leetcode" intersection of Linked Lists in JAVA