6-1 链式表的按序号查找 (16 分)

#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef struct LNode *PtrToLNode;
struct LNode {
    ElementType Data;
    PtrToLNode Next;
};
typedef PtrToLNode List;

List Read(); /* 细节在此不表 */
List Read(){ /* 细节在此不表 */
   int n;
   List a=(struct LNode*)malloc(sizeof(struct LNode));
   List head=a;
   while(1)
   {
   		scanf("%d",&n);
   if(n!=-1) {
   	a->Next=(struct LNode*)malloc(sizeof(struct LNode));
   		a=a->Next;
   	a->Data=n;
   }
   if(n==-1){
   	a->Next=NULL;
   	break;
   }
   

   }

    return head->Next;
}
ElementType FindKth( List L, int K );

int main()
{
    int N, K;
    ElementType X;
    List L = Read();
    scanf("%d", &N);
    while ( N-- ) {
        scanf("%d", &K);
        X = FindKth(L, K);
        if ( X!= ERROR )
            printf("%d ", X);
        else
            printf("NA ");
    }
    return 0;
   
}

/* 你的代码将被嵌在这里 */
ElementType FindKth(List L,int K)
{
   List q=L;
  for(int i=1;i<=K;i++)
  {
  	if(q)
  	{
  		if(i==K)
  		{
  			return q->Data;
		  }
		  q=q->Next;
	  }
	  else{
	  	return -1;
	  }
  }
  
}

猜你喜欢

转载自blog.csdn.net/weixin_42333573/article/details/88920545
今日推荐