Created
May 23, 2023 00:19
-
-
Save yanknvim/b79d9832a0a88044a73bc2e2093c9fd5 to your computer and use it in GitHub Desktop.
単方向リスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct Node { | |
int data; | |
struct Node *next; | |
} Node; | |
Node *addNode(Node *list, int data) { | |
Node* node = (Node*)malloc(sizeof(Node)); | |
if (node == NULL) { | |
return NULL; | |
} | |
node->data = data; | |
if (list == NULL) { | |
return node; | |
} | |
Node *search = list; | |
while (search->next != NULL) { | |
search = search->next; | |
} | |
search->next = node; | |
return list; | |
} | |
Node *searchEnd(Node *list) { | |
Node *search = list; | |
while (search->next != NULL) { | |
search = search->next; | |
} | |
return search; | |
} | |
Node *searchList(Node *list, int data) { | |
Node *search = list; | |
while (search->next != NULL) { | |
if (search->data == data) { | |
return search; | |
} | |
search = search->next; | |
} | |
return NULL; | |
} | |
Node *indexList(Node *list, int index) { | |
Node *search = list; | |
int counter = 0; | |
while (search->next != NULL && counter < index) { | |
search = search->next; | |
counter += 1; | |
} | |
return search; | |
} | |
void freeList(Node *list) { | |
Node *search = list; | |
Node *tmp; | |
while(search->next != NULL) { | |
tmp = search->next; | |
free(search); | |
search = tmp; | |
} | |
free(tmp); | |
} | |
int main(void) { | |
Node *list = NULL; | |
list = addNode(list, 2); | |
list = addNode(list, 5); | |
list = addNode(list, 8); | |
printf("%d\n", indexList(list, 1)->data); | |
freeList(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment