160. intersection of two linked lists

Source: Internet
Author: User

 

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

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

Begin to intersect at node C1.

 

Notes:

    • If the two linked lists have no intersection at all, returnnull.
    • The linked lists must retain their original structure after the function returns.
    • You may assume there are no cycles anywhere in the entire linked structure.
    • Your code shocould preferably run in O (n) time and use only O (1) memory.
1/** 2 * definition for singly-linked list. 3 * struct listnode {4 * int val; 5 * listnode * Next; 6 * listnode (int x): Val (x), next (null) {} 7 *}; 8 */
// The difference between a long-chain table and a short linked list before the intersection is the difference between the total length of the two linked lists.
9 class solution {10 public: 11 listnode * getintersectionnode (listnode * heada, listnode * headb) {12 if (heada = nullptr | headb = nullptr) return nullptr; 13 else {14 int Lena = 0; int lenb = 0; 15 auto * ptr1 = heada; 16 auto * ptr2 = headb; 17 while (ptr1) {18 ++ Lena; ptr1 = ptr1-> next; 19} 20 while (ptr2) {21 + + lenb; ptr2 = ptr2-> next; 22} 23 int diff = (Lena> lenb )? Lena-lenb: lenb-Lena; 24 ptr1 = heada; ptr2 = headb; 25 if (Lena> lenb) {26 while (diff --) {27 ptr1 = ptr1-> next; 28} 29} else if (lenb> Lena) {30 While (diff --) {31 ptr2 = ptr2-> next; 32} 33} 34 while (ptr1! = Ptr2) {35 ptr1 = ptr1-> next; ptr2 = ptr2-> next; 36} 37 return ptr1; 38} 39} 40 };

 

160. intersection of two linked lists

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.