在攜程面試的一道算法題,主要的考點在於兩個鏈表交叉後,以後的部分都是一樣的,只可能是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;
}
如果這麼寫呢,估計面試官就會面帶微笑了!