思路1 栈
比较简单
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *dumm1 = new ListNode(0, headA);
ListNode *dumm2 = new ListNode(0, headB);
ListNode *curA = dumm1;
ListNode *curB = dumm2;
stack<ListNode*> sA;
stack<ListNode*> sB;
while (curA)
{
sA.push(curA);
curA = curA->next;
}
while (curB)
{
sB.push(curB);
curB = curB->next;
}
if (sA.top() == sB.top())
{
ListNode *ans;
while (sA.top() == sB.top())
{
ans = sA.top();
sA.pop();
sB.pop();
}
return ans;
}
else
return nullptr;
}
};
方法2 遍历长度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *cur1 = headA;
ListNode *cur2 = headB;
int len1 = 0, len2 = 0;
while (cur1)
{
++len1;
cur1 = cur1->next;
}
while (cur2)
{
++len2;
cur2 = cur2->next;
}
cur1 = headA;
cur2 = headB;
if (len2 > len1)
{
swap(len1, len2);
swap(cur1, cur2);
}
int sub = len1 - len2;
while (sub--)
{
cur1 = cur1->next;
}
while (cur1 != cur2)
{
if (cur1->next == nullptr)
return nullptr;
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
};
方法3 官方的解答 用哈希表 更简单一些
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode *> hashA;
ListNode *curA = headA;
ListNode *curB = headB;
while (curA)
{
hashA.insert(curA);
curA = curA->next;
}
while(curB)
{
if (curB == nullptr)
return nullptr;
if (hashA.count(curB))
return curB;
curB = curB->next;
}
return nullptr;
}
};
累死了 今天就到这了 猪脑过载了