6-4 链式表的按序号查找 (10 分)

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
4 NA 1 2 5 3
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()
{
//freopen("in.txt","r",stdin);
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){ //往后移动K-1次,查找第K个元素
if(L->Next==NULL) return ERROR; //若K大于链表的长度,返回ERROR
else L=L->Next;
}
return L->Data; //返回第K个元素
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×