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.
Test instructions: To find the junction of two linked lists,
Requirement: No junction returns NULL, otherwise the address of the junction is returned.
The idea of violence: O (NM), fixed the first point of a linked list, traversing the B-linked list to see if there was the same point, then fixing the second point of the A-linked list, then iterating through the B-linked list until the same point was found.
Hash Solution: Time complexity O (n+m), Space O (n) or O (m)
Two-pointer solution: We found that as long as the two linked list length, just the same time to move the node pointer comparison one, if one of the longer, in fact, processing, the two linked list into the same length.
Solution steps:
1. Find out the length of the two linked list
2. If the same length, no processing; if one is longer, simply let the longer list take the ABS (LENGTHA-LENGTHB) step first .
3. Move the node pointer back at the same time until the junction is found.
Code:
classSolution {Private: intGetLength (listnode*head) { if(Head==null)return 0; ListNode* p=Head; intres=0; while(p->next!=NULL) { ++res;p=p->Next; } returnRes; } Public: ListNode*getintersectionnode (ListNode *heada, ListNode *headb) { if(heada==null| | Headb==null)returnNULL; intLength_a=GetLength (Heada); intlength_b=GetLength (HEADB); ListNode* pa=Heada; ListNode* pb=headb; intdis=0; if(length_a>length_b) {Dis=length_a-Length_b; while(dis>0) { --dis; PA=pa->Next; } }Else if(length_a<length_b) {Dis=length_b-length_a; while(dis>0) { --dis; PB=pb->Next; } } while(pa!=null&&pb!=null&&pa!=PB) {PA=pa->Next; PB=pb->Next; } if(Pa==pb&&pa!=null)returnPA; Else returnNULL; }};
Intersection of Linked Lists (linked list)