Created
May 28, 2019 14:46
-
-
Save LemoNode/f73b68271e23dc8cdc601a4f3a891dc4 to your computer and use it in GitHub Desktop.
c linked list test
This file contains hidden or 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> | |
| struct Node { | |
| int value; | |
| struct Node* prev, * next; | |
| struct Node* first, * last; | |
| }; | |
| void list_push(struct Node* list, struct Node* location, int value) { | |
| struct Node* node = malloc(sizeof(struct Node*)); | |
| node->value = value; | |
| node->prev = location ? location->prev : list->last; | |
| node->next = location; | |
| if (node->prev) node->prev->next = node; | |
| if (location) location->prev = node; | |
| if (location == list->first) list->first = node; | |
| if (!location) list->last = node; | |
| } | |
| void list_free(struct Node* list) { | |
| while (list->first) { | |
| struct Node* location = list->first; | |
| struct Node* prev = location->prev; | |
| struct Node* next = location->next; | |
| if (prev) prev->next = next; | |
| if (next) next->prev = prev; | |
| if (location == list->first) list->first = next; | |
| if (location == list->last) list->last = prev; | |
| free(location); | |
| } | |
| } | |
| int main(int argc, char** argv) { | |
| struct Node list = { | |
| .first = NULL, | |
| .last = NULL, | |
| }; | |
| list_push(&list, list.first, 1); | |
| list_push(&list, list.first, 3); | |
| list_push(&list, NULL, 15); | |
| list_push(&list, list.first, 4); | |
| for (struct Node* i = list.first; i != NULL; i = i->next) { | |
| printf("%i\n", i->value); | |
| } | |
| list_free(&list); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment