6-4 链式表的按序号查找 (10 分)
本题要求实现一个函数,找到并返回链式表的第K个元素。
函数接口定义:
1
| ElementType FindKth( List L, int K );
|
其中List
结构定义如下:
1 2 3 4 5 6
| typedef struct LNode *PtrToLNode; struct LNode { ElementType Data; PtrToLNode Next; }; typedef PtrToLNode List;
|
L
是给定单链表,函数FindKth
要返回链式表的第K
个元素。如果该元素不存在,则返回ERROR
。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #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 2 3
| 1 3 4 5 2 -1 6 3 6 1 5 4 2
|
输出样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #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; } List Read() { int num = 0; scanf( "%d",&num ); List list = ( List )malloc( sizeof( struct LNode ) ); list->Next = NULL; list->Data = num; List last = list; while( scanf( "%d",&num )==1&&(num!=-1)){ PtrToLNode node = ( List )malloc( sizeof( struct LNode ) ); node->Data = num; node->Next = NULL; last->Next = node; last = node; } return list;
} ElementType FindKth( List L, int K ){ if(L==NULL) return ERROR; while(--K){ if(L->Next==NULL) return ERROR; else L=L->Next; } return L->Data; }
|