leetcode链表相交
题目链接:![https://leetcode.cn/problems/intersection-of-two-linked-lists/description/]
解题思路
使用栈求解
建立两个栈,将两个链表的节点分别压入两个栈中,如果两个链表是相交的,那么从两个栈中弹出的节点一定是相同的直到弹出到相交的节点为止。
#include <stack>
struct ListNode
{
int val;
ListNode* next;
ListNode(int x = 0) : val(x), next(nullptr) {}
ListNode(int x, ListNode* n) : val(x), next(n) {}
};
//使用栈
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
{
if (headA == headB)
return headA;
std::stack<ListNode*> stA;
std::stack<ListNode*> stB;
ListNode* p = headA;
ListNode* q = headB;
while (p)
{
stA.push(p);
p = p->next;
}
while (q)
{
stB.push(q);
q = q->next;
}
while (stA.size() != 0 && stB.size() != 0)
{
if (stA.top() == stB.top())
{
stA.pop();
stB.pop();
if (stA.size() == 0)//避免单个链表不同头节点的情况
{
if (stB.top()->next == headA)
return headA;
else
return nullptr;
}
else if (stB.size() == 0)
{
if (stA.top()->next == headB)
return headB;
else
return nullptr;
}
}
else
return stA.top()->next;
}
return nullptr;
}
双指针法求解
假设链表a和链表b,a独有的部分节点数为A,b独有的部分节点数为B,两个链表公有的部分节点数为C。
p从a出发,q从b出发,遍历两个链表。p遍历完a后从b出发,q遍历完b后从a出发,直到p和q的值相等。这样两个指针走过的节点数都是相同的。p和q相等的条件就两种:p、q都是nullptr,此时两个链表不相交;p、q均不为nullptr,此时两个链表相交,交点就是p或q。
//双指针
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
{
if (headA == nullptr || headB == nullptr)
return headA;
ListNode* p = headA;
ListNode* q = headB;
while (p != q)
{
p = (p == nullptr) ? headB : (p->next);
q = (q == nullptr) ? headA : (q->next);
}
return p;
}
697

被折叠的 条评论
为什么被折叠?



