Original title Link: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
Topic: Given two single-linked list, if intersect find the first intersection.
Problem-solving idea: If two non-circular single linked lists Intersect, then the tail node must be the same node. Set two pointers, and if you traverse the table headers from both lists, you obviously cannot find the intersection. But if the long list is truncated and the two pointers are traversed at the same time, then the first two-pointer-equal nodes are obviously the desired node. If you go to the end of the chain and do not intersect, the two linked lists do not intersect.
Class Solution {public: listnode *getintersectionnode (ListNode *heada, ListNode *headb) { if (heada==null| | Headb==null) return NULL; ListNode *p1,*p2; p1=heada,p2=headb; int lena=0,lenb=0; while (p1) { lena++; p1=p1->next; } while (p2) { lenb++; p2=p2->next; } p1=heada,p2=headb; while (LENA<LENB) { p2=p2->next; lena++; } while (Lenb<lena) { p1=p1->next; lenb++; } while (P1&&P2) { if (P1==P2) return p1; p1=p1->next; p2=p2->next; } return NULL; }};
Because there is no ring, so the topic is relatively simple. The topic is more classic, can be extended to have the ring case, we can consider ha.
Intersection of Linked Lists--leetcode