您的位置:首页 > 其它

LeetCode_intersection-of-two-linked-lists

2015-09-14 10:16 260 查看
https://leetcode.com/problems/intersection-of-two-linked-lists/

题意:判断两个链表是否有公共交点;
思路:先求每个链表的长度,然后把最长链表移动两个链表的长度差,然后两链表同步判断,即可求出是否有公共交点;
/**
* 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)
return nullptr;
if(!headB)
return nullptr;

ListNode *p,*q;
p = headA;
q = headB;
int cntA = 0,cntB = 0;

while(p){
cntA++;
p = p->next;
}

while(q){
cntB++;
q = q->next;
}

p = headA;//恢复p指向链表的开始处
q = headB;//恢复q指向链表的开始处
int i = abs(cntA-cntB);

if(cntA > cntB){
while(i--){
p = p->next;
}
}
else{
while(i--){
q = q->next;
}
}
while(p){
if(p == q){
return p;
}
p = p->next;
q = q->next;
}

return nullptr;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: