题目要求:
简单来说就是用高效的算法来求倒数第k个元素。
方法1: 就先遍历一遍求出单链表的长度,用单链表的长度减去k,即为从前往后要走走的步数。走了n+n-k次。
int length(Linklist &list){
num=0;
LNode *p;
p=list->link;
if(p==NULL)
num=0;
while(p){
num++;
p=p->link;
}
return num;
}
bool find_k(Linklist &list,int k){//总共遍历n+k次
LNode *p;
int temp=0;
int n=length(list)-k+1;//必须先执行length(list)
p=list->link;
if(p==NULL)
cout<<"This list is empty !"<<endl;
if(k>length(list))
cout<<"Have no find this location !"<<endl;
while(p){
temp++;
if(temp==n){
cout<<"date_k:"<<p->date<<endl;
return true;
}
else
p=p->link;
}
return false;
}
注: 这种方法很中规中矩,不能达到高效,所以采用快速查找的方法。
快速查找思想:
假设k=2,输出元素4。p1往前走k-1步。当p1指向表的尾时,p2正好是要输出的元素。
方法2: 就是通过两个指针p1,p2,首先让p1往前走k-1步,然后让p1,p2一起往前走,当p1走到尾的时候,p2即为倒数第k个。总共走了n次。时间复杂度为O(n).
bool find(Linklist &list,int k){//遍历n次
LNode *p1,*p2;
p1=p2=list->link;
for(int i=1;i<=k-1;i++)//p1往前走k-1个(假设起始在倒数k处,往后走k-1个就到尾了)
p1=p1->link;
while(p1->link){
p1=p1->link;
p2=p2->link;
}
cout<<"date_k:"<<p2->date<<endl;
}