Intersection of Linked Lists--leetcode

Source: Internet
Author: User

Original title Link: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/

Topic: Given two single-linked list, if intersect find the first intersection.

Problem-solving idea: If two non-circular single linked lists Intersect, then the tail node must be the same node. Set two pointers, and if you traverse the table headers from both lists, you obviously cannot find the intersection. But if the long list is truncated and the two pointers are traversed at the same time, then the first two-pointer-equal nodes are obviously the desired node. If you go to the end of the chain and do not intersect, the two linked lists do not intersect.

Class Solution {public:    listnode *getintersectionnode (ListNode *heada, ListNode *headb) {        if (heada==null| | Headb==null)            return NULL;        ListNode *p1,*p2;        p1=heada,p2=headb;        int lena=0,lenb=0;        while (p1) {            lena++;            p1=p1->next;        }        while (p2) {            lenb++;            p2=p2->next;        }        p1=heada,p2=headb;        while (LENA<LENB) {            p2=p2->next;            lena++;        }        while (Lenb<lena) {            p1=p1->next;            lenb++;        }        while (P1&&P2) {            if (P1==P2)                return p1;            p1=p1->next;            p2=p2->next;        }        return NULL;    }};

Because there is no ring, so the topic is relatively simple. The topic is more classic, can be extended to have the ring case, we can consider ha.

Intersection of Linked Lists--leetcode

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.