#include #include #include #define MAX_LINE 1024 struct node { int value; struct node *next; }; int listGetIndex(struct node *list, int index); struct node *readList(void); struct node *newNode(int value); void printList(struct node *list); void freeList(struct node *list); int main(void) { printf("Enter list values: "); struct node *list = readList(); printf("List: "); printList(list); printf("Enter index: "); int index = 0; scanf("%d", &index); int value = listGetIndex(list, index); printf("Index %d is %d\n", index, value); freeList(list); } //////////////////////////////////////////////////////////////////////// int listGetIndex(struct node *list, int index) { // TODO return 0; } //////////////////////////////////////////////////////////////////////// struct node *readList(void) { char line[MAX_LINE]; fgets(line, MAX_LINE, stdin); struct node *list = NULL; struct node *curr = NULL; char *token = strtok(line, " \n\t"); while (token != NULL) { int value; if (sscanf(token, "%d", &value) == 1) { struct node *node = newNode(value); if (list == NULL) { list = node; } else { curr->next = node; } curr = node; } token = strtok(NULL, " \n\t"); } return list; } struct node *newNode(int value) { struct node *n = malloc(sizeof(*n)); if (n == NULL) { fprintf(stderr, "error: out of memory\n"); exit(EXIT_FAILURE); } n->value = value; n->next = NULL; return n; } void printList(struct node *list) { printf("["); for (struct node *curr = list; curr != NULL; curr = curr->next) { printf("%d", curr->value); if (curr->next != NULL) { printf(", "); } } printf("]\n"); } void freeList(struct node *list) { struct node *curr = list; while (curr != NULL) { struct node *temp = curr; curr = curr->next; free(temp); } }