您的位置:首页 > 其它

《leetCode》:Intersection of Two Linked Lists

2016-03-17 21:54 344 查看

题目

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
begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.


思路

这个题目就是找两个链表的公共节点,比较简单,自己也碰到过很多次,思路见代码,这里不再描述。

struct ListNode {
int val;
struct ListNode *next;
};
int getListLen(struct ListNode *head){
if(head==NULL){
return 0;
}
struct ListNode *cur=head;
int len=0;
while(cur!=NULL){
len++;
cur=cur->next;
}
return len;
}
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA==NULL||headB==NULL){
return NULL;
}
//计算出链表A、B的长度差
int listALen=getListLen(headA);
int listBLen=getListLen(headB);
struct ListNode *curLargeList=NULL;
struct ListNode *curLowList=NULL;
int dif=0;
if(listALen>=listBLen){//注意:等号如果不写,下面这个if要写
dif=listALen-listBLen;
curLargeList=headA;
curLowList=headB;
}
if(listALen<listBLen){
dif=listBLen-listALen;
curLargeList=headB;
curLowList=headA;
}
while(dif>0){
curLargeList=curLargeList->next;
dif--;
}
while(curLargeList!=curLowList){
curLargeList=curLargeList->next;
curLowList=curLowList->next;
}
return curLargeList;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: