您的位置:首页 > 编程语言 > C语言/C++

leetcode 日经贴,Cpp code -Intersection of Two Linked Lists

2015-04-22 16:16 288 查看
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) {
ListNode *ca = headA, *cb = headB;
int len1 = 0, len2 = 0;
while (ca && ca->next) {
++len1;
ca = ca->next;
}
while (cb && cb->next) {
++len2;
cb = cb->next;
}
if (!ca || !cb || ca != cb) {
return NULL;
}
ca = headA;
cb = headB;
while (len1 > len2) {
ca = ca->next;
--len1;
}
while (len2 > len1) {
cb = cb->next;
--len2;
}
while (ca != cb) {
ca = ca->next;
cb = cb->next;
}
return ca;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: