请写一个程序,找到两个单链表最开始的交叉节点。
注意事项:
- 如果两个链表没有交叉,返回null。
- 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
样例:
下列两个链表:
在节点 c1 开始交叉。
挑战 :
需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
#ifndef C380_H
#define C380_H
#include<iostream>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int val)
{
this->val = val;
this->next = NULL;
}
};
class Solution {
public:
/*
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode * getIntersectionNode(ListNode * headA, ListNode * headB) {
// write your code here
if (headA == NULL || headB == NULL)
return NULL;
int lenA = 0, lenB = 0;
ListNode *p = headA, *q = headB;
while (p->next!=NULL)
{
lenA++;
p = p->next;
}
lenA++;
while (q->next!=NULL)
{
lenB++;
q = q->next;
}
lenB++;
if (p != q)
return NULL;
ListNode *p1 = headA, *q1 = headB;
if (lenA > lenB)
{
while (lenA !=lenB)
{
p1 = p1->next;
lenA--;
}
while (p1!=NULL&&q1!=NULL)
{
if (p1 == q1)
{
return p1;
break;
}
q1 = q1->next;
p1 = p1->next;
}
}
else
{
while (lenA != lenB)
{
q1 = q1->next;
lenB--;
}
while (p1 != NULL&&q1 != NULL)
{
if (p1 == q1)
{
return q1;
break;
}
q1 = q1->next;
p1 = p1->next;
}
}
}
};
#endif