Intersection of Linked Lists--Leetcode

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.


Notes:

    • If The linked lists has no intersection at all, return null .
    • The linked lists must retain their original structure after the function returns.
    • You may assume there is no cycles anywhere in the entire linked structure.
    • Your code should preferably run in O (n) time and use only O (1) memory.



Algorithm one:

Set up 2 pointers, each pointing to a linked list head.

Simultaneously forward until the same node is found.

When the pointer traverses the tail of the linked list, the pointer points back to the head of the other linked list.

The principle that the algorithm works is:

Set both to have intersections.

The number of nodes in a linked list is M + C

The number of nodes in the B-linked list is n + C

Where c is the number of intersecting nodes. That is, the number of nodes that are shared.

M, n is the number of distinct sections of the linked list.

Then there is M + c + N = = n + C + M

The meaning of this formula is:

Set P1 initial point to a linked list, P2 initial point to the B linked list.

When P1 passes through the A-linked list (M+C nodes) and traverses the n nodes of the B-linked list, p1 comes to the intersection point.

And at this time P2 also happened to the intersection point. That is, traversing the B-linked list (N+C nodes), and traversing the A-linked list of M nodes.

So we can find the intersection.


The following code, when there is no intersection, how to exit the loop.

P1 after traversing the A-linked list and traversing the B-linked list, at this point, it goes to the end of the B-linked list;

At this time, p2, traversing the B-linked list, also must be at the end of the list of a chain, because two pointers are completed at the same time two linked list traversal.

At this point, the P1 and P2 pointers are both empty.

So when there is no intersection of two linked lists, the number of nodes traversed is the sum of two linked lists.


Also, if two linked lists are of equal length, they will end prematurely. That is, you simply traverse through a list length.


The following line of code is the key to dealing with non-existent intersections:

if (P1 = = p2)                return p1;

The actual execution time on the Leetcode is 52ms.

/** * Definition for singly-linked list. * struct ListNode {*     int val; *     ListNode *next; *     listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public:    listnode *getintersectionnode (ListNode *heada, ListNode *headb) {        if (!heada | |!headb)            return NULL;                ListNode *p1 = Heada;        ListNode *p2 = headb;        while (P1! = p2) {            P1 = p1->next;            P2 = p2->next;                        if (P1 = = p2)                return p1;                            if (!p1) p1 = headb;            if (!p2) P2 = Heada;        }        return p1;}    ;
Algorithm Source:
Https://leetcode.com/discuss/17278/accepted-shortest-explaining-algorithm-comments-improvements


Algorithm two

This algorithm is a more common idea:

1. The length of the linked list is counted first.

2. Set up 2 pointers, and point to two linked lists in a table. And make a longer linked list, advance step pointer. The number of steps in the step, which is the difference in length.

3. Then make a comparison and step into the 2 needle pointers at the same time.


The actual execution time of this algorithm on Leetcode is 56ms.

In contrast, the time complexity of this algorithm is not worse than algorithm one.

Class Solution {public:    listnode *getintersectionnode (ListNode *heada, ListNode *headb) {        if (!heada | |!headb) C2/>return NULL;                int sizea = 0;        ListNode *p = Heada;        while (p) {            p = p->next;            ++sizea;        }                int Sizeb = 0;        p = headb;        while (p) {            p = p->next;            ++sizeb;        }                while (Sizea > Sizeb) {            Heada = heada->next;            --sizea;        }                while (Sizeb > Sizea) {            headb = headb->next;            --sizeb;        }                while (Heada && heada! = headb) {            Heada = heada->next;            HEADB = headb->next;        }                return heada;}    ;


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.