This requires implementing a function that finds and returns the K-element of the linked table.
function Interface Definition:
ElementType findkth (List L, int K);
Where the list structure is defined as follows:
typedef struct Lnode *ptrtolnode;struct lnode { ElementType Data; Ptrtolnode Next;}; typedef ptrtolnode List;
L is given a single linked list, the function findkth to return the K element of the linked table. If the element does not exist, an error is returned.
Example of a referee test procedure:
#include <stdio.h> #include <stdlib.h> #define ERROR-1TYPEDEF int elementtype;typedef struct Lnode * Ptrtolnode;struct Lnode { ElementType Data; Ptrtolnode Next;}; typedef ptrtolnode List; List Read (); /* Details are not in this table */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 */
Input Sample:
1 3 4 5 2-163 6 1 5 4 2
Sample output:
4 NA 1 2 5 3
Code
#include <stdio.h> #include <stdlib.h> #define ERROR-1TYPEDEF int elementtype;typedef struct Lnode * Ptrtolnode;struct Lnode {ElementType Data; Ptrtolnode Next;}; typedef ptrtolnode List; List Read (); /* Details are not in this table */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;} List Read () {int num = 0; scanf ("%d", &num); if (-1 = = num) {return NULL; } List List = (list) malloc (sizeof (struct lnode)); List last = list; List->data = num; List->next = NULL; scanf ("%d", &num); while (-1! = num) {ptrtolnode node = (List) malloc (sizeof (struct lnode)); Node->data = num; Node->next = NULL; Last->next = node; last = node; scanf ("%d", &num); } return list;} Returns the K of a linked tableElements. If the element does not exist, returns Errorelementtype findkth (List L, int K) {if (NULL = = L) {return ERROR; } if (K <= 0) {return ERROR; } ptrtolnode node = L; int i = 1; while (NULL! = node && i < K) {//printf ("data =%d\n", node->data); if (NULL = = Node->next) {break; } node = node->next; i++; } if (i< K) {return ERROR; }else{return node->data; }}
pta-data structure and algorithm topic set (Chinese)--4-4-based search for chained tables