6-4 鏈式表的按序號查找


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;
}

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM