Github-jz-52 – source :large_blue_diamond: Programmer romance
Problem description
Enter two linked lists to find their first common node.
Method 1:
- Execution time: 68 ms, beating 29.97% of all C++ commits
- Memory consumption: 14.4 MB, beating 100.00% of all C++ commits
Algorithm complexity O(n)
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
//* Two traversal Pointers
ListNode* p = headA;
ListNode* q = headB;
while(p ! = q) {if (p==nullptr) {
p = headB;
}
else {
p = p->next;
}
if (q == nullptr) {
q = headA;
}
else{ q = q->next; }}returnp; }};Copy the code