问题
思路
朴素的思路,枚举就好了。两遍循环。
代码
/**
* 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 || !headB)
return NULL;
ListNode* p = headA;
while( p ){
ListNode* q = headB;
while(q){
if(p->val == q->val){
return p;
}
else
q = q->next;
}
p = p->next;
}
return NULL;
}
};
思路1
看了解题报告之后发现更简单的办法,主要是链表不一样长的时候,要进行处理。处理到二者剩余长度一致时,进行便利,相同返回即可。
代码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) {
if( !headA || !headB )
return NULL;
int lenA = 0;
int lenB = 0;
for(ListNode* p = headA; p != NULL; p=p->next) lenA++;
for(ListNode* p = headB; p != NULL; p=p->next) lenB++;
if(lenA > lenB)
{
int diff = lenA- lenB;
for( int i = 0; i < diff; ++i ) headA = headA->next;
}
else if( lenA < lenB )
{
int diff = lenB - lenA;
for( int i = 0; i < diff; ++i ) headB = headB->next;
}
while( headA && headB ){
if( headA->val == headB->val )
return headA;
else{
headA = headA->next;
headB = headB->next;
}
}
return NULL;
}
};