Intersection of Linked Lists
Total Accepted: 74850 Total Submissions: 246823 Difficulty: Easy
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide TagsLinked List
C + + code:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {Public:listnode *getintersectionnode (ListNode *heada, ListNode *headb) {if (!headA | |!headB) return NULL; int cnta=0,cntb=0; ListNode *pa=heada, *pb=headb; while (PA) {pa=pa->next; cnta++; } while (Pb) {pb=pb->next; cntb++; } pa=heada,pb=headb; while (Cntb < CntA) {pa=pa->next; cnta--; } while (CntA < CNTB) {pb=pb->next; cntb--; } while (PA && pb) {if (PA = = pb) break; else{pa=pa->next; pb=pb->next; }} return PA; }};
Leetcode:intersection of Linked Lists