class Solution {
public:
ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
auto p = headA, q = headB;
int la = 0, lb = 0;
for (auto t = headA; t; t = t->next) la ++;
for (auto t = headB; t; t = t->next) lb ++;
int k = la - lb;
if (la < lb) {
p = headB, q = headA;
k = lb - la;
}
while(k --) {
p = p->next;
}
while(p) {
if (p == q) return p;
p = p->next;
q = q->next;
}
return nullptr;
}
};
```cpp
class Solution {
public:
ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
auto p = headA, q = headB;
while(p != q) {
if(p) p = p->next;
else p = headB;
if (q) q = q->next;
else q = headA;
}
return p;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3697a75066ce848c8bcb8c6ad7e3a13e.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d87be7d7e90280bb4e65143a938954d5.png)
class Solution {
public:
ListNode* filterList(ListNode* head) {
bool st[10001] = {};
st[abs(head->val)] = true;
for (auto p = head; p->next;) {
int x = abs(p->next->val);
if (st[x]) {
auto q = p->next;
p->next = q->next;
delete q;
} else {
p = p->next;
st[x] = true;
}
}
return head;
}
};