In the task, you need to find the point of merging of simply connected lists and display the value in this node. I made it very simple: if the lists are of different lengths, I calculate the difference of their lengths, this is the number of redundant elements. I skip the extra elements and start moving along the two lists at the same time until a common point is found.
Is it possible to solve the problem by inverting lists? I on a piece of paper drew various variants of inverting one list or two at once, considered a variant of passage from the end, but nothing came to mind.
Is there any segolts in my code?
/* Find merge point of two linked lists Node is defined as struct Node { int data; Node* next; } */ // ΠΠΎΠ΄ΡΡΠ΅Ρ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²Π° ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² Π² ΡΠΏΠΈΡΠΊΠ΅ int count(Node *head) { int c = 0; while(head) { c++; head = head->next; } return c; } int FindMergeNode(Node *headA, Node *headB) { if(headA && headB) // ΠΡΠ»ΠΈ ΠΎΠ΄ΠΈΠ½ ΠΈΠ· ΡΠΏΠΈΡΠΊΠΎΠ² Π½Π΅ ΠΏΡΡΡ { int len_a = count(headA); // ΠΡΡΠΈΡΠ»Π΅Π½ΠΈΠ΅ Π΄Π»ΠΈΠ½ ΡΠΏΠΈΡΠΊΠΎΠ² A ΠΈ B int len_b = count(headB); int diff = std::abs(len_a - len_b); // Π Π°Π·Π½ΠΎΡΡΡ ΠΌΠ΅ΠΆΠ΄Ρ Π΄Π»ΠΈΠ½Π°ΠΌΠΈ ΡΠΏΠΈΡΠΊΠΎΠ² for(int i = 0; i < diff; i++) // ΠΡΠΎΠΏΡΡΠΊ Π»ΠΈΡΠ½ΠΈΡ
ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² Π² ΡΠ°ΠΌΠΎΠΌ Π΄Π»ΠΈΠ½Π½ΠΎΠΌ ΡΠΏΠΈΡΠΊΠ΅ (len_a > len_b) ? headA = headA->next : headB = headB->next; while(headA != NULL && headB != NULL) { if(headA == headB) // ΠΡΠ»ΠΈ Π½Π°ΠΉΠ΄Π΅Π½Π° ΡΠΎΡΠΊΠ° ΡΠ»ΠΈΡΠ½ΠΈΡ (Π°Π΄ΡΠ΅ΡΠ° Π½ΠΎΠ΄ ΡΠ°Π²Π½Ρ) return headA->data; headA = headA->next; headB = headB->next; } } return 0xDEADBEEF; } 