6-4 鏈式表的按序號查找(10 分)
本題要求實現一個函數,找到並返回鏈式表的第K個元素。
函數接口定義:
ElementType FindKth( List L, int K );
其中List
結構定義如下:
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode List;
L
是給定單鏈表,函數FindKth
要返回鏈式表的第K
個元素。如果該元素不存在,則返回ERROR
。
裁判測試程序樣例:
#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;
}
/* 你的代碼將被嵌在這里 */
輸入樣例:
1 3 4 5 2 -1
6
3 6 1 5 4 2
輸出樣例:
4 NA 1 2 5 3
思路:簽個到晚安😁
ElementType FindKth(List L, int K) { if (L == NULL||K<=0)return ERROR; List list = L; for(int i=1;i<K;i++){ if (list->Next == NULL) return ERROR; list = list->Next; } return list->Data; }