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

leetcode_c++:链表:Intersection of Two Linked Lists(160)

2016-07-18 16:08 429 查看
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: a1 → a2



c1 → c2 → c3



B: b1 → b2 → b3

O(N)

class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//计算表的长度
int lenA=getListlength(headA);
int lenB=getListlength(headB);
if(lenA<=0 || lenB<=0) return NULL;

if(lenA<lenB)
swap(headA,headB);

//move head of the listA,make both of Lists are same length
for(int i=0;i<abs(lenA-lenB);i++)
headA=headA->next;

while(headA!=headB){
headA=headA->next;
headB=headB->next;
}

return headA;

}
private:
inline int getListlength(ListNode* head){
int len=0;
while(head!=NULL){
head=head->next;
len++;
}
return len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: