在携程面试的一道算法题,主要的考点在于两个链表交叉后,以后的部分都是一样的,只可能是Y型的交叉而不可能出现X型的交叉,
首先定义节点:
struct Node{
int data;
Node* next;
};
最笨的方法是遍历所有的节点进行比较,比如
Node* ifCrossed(Node* list1,Node* list2){
Node* one = list1;Node* two = list2;
while(one){
while(two){
if(two==one) return one;
two=two->next;
}
one=one->next;
}
return NULL;
}
如果这么写,那么那么你跪了,面试官肯定会认为你差劲的,而应该如下解决
Node* ifCrossed(Node* list1,Node* list2){
Node* one = list1;Node* two = list2;
int len1 = 0,len2 = 0;
while(one) {len1++;one=one->next;}
while(two) {len2++;two=two->next;}
one = list1;two = list2;
if(len1>len2){
for(int i = 0; i < len1-len2;i++) one=one->next;
}else{
for(int i = 0; i < len2-len1;i++) two=two->next;
}
while(one!=two&&one&&two){
one=one->next;
two=two->next;
}
return one;
}
如果这么写呢,估计面试官就会面带微笑了!