在PTA上一直显示段错误,麻烦各位帮我看看出了什么问题
ElementType FindKth( List L, int K ){
PtrToLNode ptrl = L;
int i = 1;
if( ptrl!=NULL){
while( i<K){
ptrl = ptrl->Next;
i++;
}
if( i==K ){ //注:不能只写 if(i==k) 因为有可能传入的链表L为空,但K又恰好为1
return(ptrl->Data);
}
else{
return ERROR;
}
}
else{
return ERROR;
}
}
假设List L长度为3,K=10 程序会怎么样?
这么改:
ElementType FindKth(List L, int K) {
PtrToLNode ptrl = L;
int i = 0;
if (L->Lenght == 0) return ERROR;
if (K < 1 || K > L->Lenght) {
return ERROR;
}
else {
while (ptrl != NULL && i < K) {
ptrl = ptrl->Next;
i++;
}
if (i == K) {
return(ptrl->Data);
}
else {
return ERROR;
}
}
}