LeetCode Intersection of Two Linked Lists solution report, leetcode

Source: Internet
Author: User

LeetCode Intersection of Two Linked Lists solution report, leetcode
Https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
Calculate the first public node of the two linked lists. If there is no public node, null is returned.

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

Solution:
1) if the last node of the two linked lists is the same, the two linked lists must have an intersection.
2) Calculate the length of the two linked lists respectively, and then move the linked list with the length forward: LengA-LengB, align the two linked lists, and traverse them together until the first same 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;    }}


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.