链式表的按序号查找
本題要求實現一個函數,找到并返回鏈式表的第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
AC code: 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個元素 }
?
?
轉載于:https://www.cnblogs.com/ruruozhenhao/p/9700631.html
總結
- 上一篇: 羽毛球拍多少钱啊?
- 下一篇: python 全栈开发,Day132(玩