您的位置:首页 > 其它

[Leetcode 160] Intersection of Two Linked Lists

2015-07-27 09:51 465 查看

题目



给定两个链表,求两个单链表的交点。要求时间复杂度为O(n),空间复杂度为O(1)

分析



代码

采用方法二

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getLength(ListNode* head){
int length = 0;
while(head){
length++;
head = head->next;
}
return length;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL || headB==NULL){
return NULL;
}
int lenA = getLength(headA);
int lenB = getLength(headB);
if(lenA >= lenB){
for(int i=lenA-lenB; i>0; headA=headA->next,i--)
;
}else{
for(int i=lenB-lenA; i>0; headB=headB->next,i--)
;
}
for(; headA && headB && headA!=headB; headA=headA->next, headB=headB->next)
;
return (headA==headB)?headA:NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: