如何在循环单链表的查找某个位置的值
int GetElem(CLinkList *L,int i,ElemType &e) {
int j=0;
CLinkList *p=L;
if(p->next==L)
return 0;
while(j<i-1&&p->next!=L)
{
j++;
p=p->next;
}
e=p->data;
return 1;
}
我这样的算法总是找不到最后一个元素,希望各位帮我解决这个问题!多谢!
//我这样的算法总是找不到最后一个元素,希望各位帮我解决这个问题!多谢! #include <stdio.h> #include <malloc.h> typedef struct node { short data; struct node * next; }CLinkList; //构建担循环链表 CLinkList * create_clist( CLinkList *L ) { CLinkList *header, *temp; short d; while( scanf("%d", &d) ) { if( NULL == L ) { L = (CLinkList *) malloc (sizeof(CLinkList)); L->data = d; L->next = L; header = L; } else { temp = (CLinkList *) malloc (sizeof(CLinkList)); temp->data = d; temp->next = header->next; header->next = temp; header = temp; } } return L; } void print( CLinkList *L ) { CLinkList *temp = L; if( NULL == L ) { printf("\tno data!\n"); return; } do { printf("%d ", temp->data ); temp = temp->next; }while( temp != L ); printf("\n"); return; } int GetElem( CLinkList *L, int i ) { CLinkList *temp = L; short return_e; if( NULL == L ) { printf("\tno data!\n"); return 0; } if( 0 == i ) { printf("\ti=!0\n"); return 0; } do { return_e = temp->data; temp = temp->next; }while( --i && temp != L ); if( 0 != i ) { printf("\tcann't found!\n"); return 0; } return return_e; } int main() { CLinkList *L = NULL; L = create_clist( L ); print( L ); printf("%d \n", GetElem( L, 7 ) ); return 0; }