#include <iostream>
using namespace std;
typedef struct Node
{
char data;
struct Node *next;
} SNode;
int listlen(SNode *s)
{
int len = 0;
while (s->next != nullptr)
{
len++;
s = s->next;
}
return len;
}
SNode *find_Node(SNode *str1, SNode *str2)
{
int m, n;
m = listlen(str1);
n = listlen(str2);
SNode *p, *q;
for (p = str1; m > n; m--)
{
p = p->next;
}
for (q = str2; m < n; n--)
{
q = q->next;
}
while (p->next != nullptr && p->next != q->next)
{
p = p->next;
q = q->next;
}
return p->next;
}
SNode *createList(const string &str)
{
SNode *head = new SNode;
SNode *current = head;
for (char ch : str)
{
current->next = new SNode{ch, nullptr};
current = current->next;
}
return head;
}
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution1
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode *curA = headA;
ListNode *curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL)
{
lenA++;
curA = curA->next;
}
while (curB != NULL)
{
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
if (lenB > lenA)
{
swap(lenA, lenB);
swap(curA, curB);
}
int gap = lenA - lenB;
while (gap--)
{
curA = curA->next;
}
while (curA != NULL)
{
if (curA == curB)
{
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
class Solution2
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
auto p = headA, q = headB;
while (p != q)
{
p = p ? p->next : headB;
q = q ? q->next : headA;
}
return p;
}
};