6-2 链式表的按序号查找
生活随笔
收集整理的這篇文章主要介紹了
6-2 链式表的按序号查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
6-2 鏈式表的按序號查找 (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);elseprintf("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 ) {int cnt = 0;while(L){cnt++;if(cnt == K){return L->Data;}L = L->Next;}return ERROR; }總結
以上是生活随笔為你收集整理的6-2 链式表的按序号查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 6-1 求链式表的表长
- 下一篇: 6-3 两个有序链表序列的合并