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.
Besides the difficulty of reading the subject, the problem is all right. A very good topic to do.
The code is as follows:
//* Definition for singly-linked list. structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}};classSolution { Public: ListNode*getintersectionnode (ListNode *heada, ListNode *headb) { if(Heada = = NULL | | headb = =NULL)returnNULL; intLengtha=1, lengthb=1; ListNode*cora = Heada, *corb =headb; while(Cora->next! =NULL) {Cora= cora->Next; Lengtha++; } while(Corb->next! =NULL) {Corb= corb->Next; LENGTHB++; } if(Cora->val! = corb->val)returnNULL; intdif = Lengtha-LENGTHB; Cora= Heada, Corb =headb; if(DIF >=0) { while(DIF) {dif--; Cora= cora->Next; } } Else
{ while (dif) { dif++ ; = Corb->next; } } while (Cora! = NULL) { if (cora = = Corb )return Cora ; Else { = cora->next; = Corb->Next;}}} ;
Happyleetcode42:intersection of Linked Lists