"Leetcode" intersection of the Linked Lists in JAVA

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.