Leecode刷题
- 题目描述
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
- 代码
/**
* 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)
{
if(headA==NULL||headB==NULL)
return NULL;
stack<ListNode*> p1;//将链表压入栈后从后往前比较
stack<ListNode*> p2;
while(headA)
{
p1.push(headA);
headA=headA->next;
}
while(headB)
{
p2.push(headB);
headB=headB->next;
}
if(p1.top()!=p2.top())//如果两个链表最后元素不相等,则肯定不是相交链表
return NULL;
ListNode *answer;
while(!p1.empty()&&!p2.empty()&&p1.top()==p2.top())
{
answer=p1.top();
p1.pop();
p2.pop();
}
return answer;
}
};