6-2 Search by serial number of linked list (10 points)
This question requires implementing a function to find and return the Kth element of the linked list.
Function interface definition:
ElementType FindKth( List L, int K );
The List structure is defined as follows:
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode List;
L is a given singly linked list, the function FindKth should return the Kth element of the linked list. If the element does not exist, ERROR is returned.
Sample referee test procedure:
#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(); /* 细节在此不表 */
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;
}
/* Your code will be embedded here */
Input sample:
1 3 4 5 2 -1
6
3 6 1 5 4 2
Sample output:
4 NA 1 2 5 3
ElementType FindKth( List L, int K )
{
int cnt = 0;
while(L)
{
cnt++;
if(cnt == K)
{
return L->Data;
}
L = L->Next;
}
return ERROR;
}