160. Intersection of Two Linked Lists, intersectionlinked

Source: Internet
Author: User

160. Intersection of Two Linked Lists, intersectionlinked

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.

Search for the first intersection of two linked lists

 

1/** 2 * Definition for singly-linked list. 3 * struct ListNode {4 * int val; 5 * struct ListNode * next; 6 *}; 7 */8 struct ListNode * getIntersectionNode (struct ListNode * headA, struct ListNode * headB) {9 int a, B, I; 10 struct ListNode * acur; 11 struct ListNode * bcur; 12 acur = headA; 13 bcur = headB; 14 a = B = 0; 15 while (acur! = NULL | bcur! = NULL) // calculate the length of two linked lists: 16 {17 if (acur! = NULL) 18 {19 a ++; 20 acur = acur-> next; 21} 22 if (bcur! = NULL) 23 {24 B ++; 25 bcur = bcur-> next; 26} 27} 28 acur = headA; 29 bcur = headB; 30 if (a> B) // long first | a-B | step, let the remaining length of the two linked lists be the same as 31 {32 I = a-B; 33 while (I) 34 {35 acur = acur-> next; 36 I --; 37} 38} 39 else40 {41 I = B-a; 42 while (I) 43 {44 bcur = bcur-> next; 45 I --; 46} 47} 48 while (acur! = NULL) // judge the first intersection node of the two linked lists 49 {50 if (acur = bcur) 51 break; 52 acur = acur-> next; 53 bcur = bcur-> next; 54} 55 if (acur! = NULL) 56 return acur; 57 return NULL; 58 59}

 

Related Article

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.