Leetcode intersection of the Linked Lists problem Solving report

Source: Internet
Author: User

https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
The first public node of the two list is evaluated, and NULL is returned if no public node exists.

A:          a1→a2                                        c1→c2→c3                               B:     b1→b2→b3

Problem Solving Ideas:
1) If the last node of the two list is the same, then there must be an intersection between the two linked lists.
2) The lengths of the two linked lists are calculated, and then the long-length linked list is moved forward: LENGA-LENGB, aligns the two linked lists, and then traverses together until the first node is found.

public class Solution {public ListNode Getintersectionnode (ListNode heada, ListNode headb) {if (heada==null ||        Headb==null) {return null;        } int lengtha = 1;                int LENGTHB = 1;        ListNode Itera = Heada;            while (itera.next!=null) {itera = Itera.next;        lengtha++;        } ListNode iterb = headb;            while (iterb.next!=null) {iterb = Iterb.next;        lengthb++;        } if (Itera!=iterb) {return null;            } if (LENGTHA>LENGTHB) {int tmp = LENGTHA-LENGTHB;                while (tmp>0) {Heada = Heada.next;            tmp--;            }} else {int tmp = Lengthb-lengtha;                while (tmp>0) {headb = Headb.next;            tmp--;           }} while (heada!=headb) {Heada = Heada.next; HEADB = Headb.next;    } return Heada; }}


Leetcode intersection of the Linked Lists problem Solving report

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.