当前位置:网站首页>6-4 search by serial number of linked list

6-4 search by serial number of linked list

2022-07-05 06:37:00 timingzj

This question requests to realize a function , Find and return the second row of the linked list K Elements .

Function interface definition :

ElementType FindKth( List L, int K );

among List The structure is defined as follows :

typedef struct LNode *PtrToLNode;
struct LNode {
    ElementType Data;
    PtrToLNode Next;
};
typedef PtrToLNode List;

L Is a given single linked list , function FindKth To return the second K Elements . If the element doesn't exist , Then return to ERROR

Sample referee test procedure :

#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(); /*  Details are not shown here  */

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

/*  Your code will be embedded here  */

sample input :

1 3 4 5 2 -1
6
3 6 1 5 4 2

sample output :

4 NA 1 2 5 3 

Code :

ElementType FindKth( List L, int K )
{
    int i = 1;
    while(L)
    {
        if(i == K)
            return L->Data;
        L = L->Next;
        i++;
    }
    return ERROR;
}

原网站

版权声明
本文为[timingzj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140603055277.html