Topic:
Write a program that finds the starting node where two single-linked tables intersect. For example, the following two linked lists: A: a1→a2 c1→c2→c3 B: b1→b2→b3 intersect at node C1. Note: If two linked lists do not have an intersection, NULL is returned. After returning the results, the two linked lists still have to be kept in their original structure. You can assume that there are no loops in the entire list structure. The program tries to satisfy the O (n) time complexity and uses only O (1) of memory.
Solving algorithm:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {public:int lengthlist (struct ListNode *head) {int count = 0; if (head = = NULL) {return 0; } while (head) {head = head->next; count++; } return count; } ListNode *getintersectionnode (ListNode *heada, ListNode *headb) {int L1 = lengthlist (Heada); int L2 = lengthlist (HEADB); ListNode * Node1 = NULL; ListNode * Node2 = NULL; if (Heada = = NULL | | headb = = NULL) {return null; } if (L1 > L2) {while (L1!=L2) {Heada = heada->next; l1--; }} if (L1 < L2) {while (L1!=L2) {headb = headb->next; l2--; }} while (heada->next&&headb->next&& heada!=headb) {Heada = heada->next; HEADB = headb->next; } if (heada!=headb) {return NULL; }else{return Heada; } }};
"Intermediate algorithm" 9. Intersect linked list