Created
November 16, 2023 13:17
-
-
Save jw910731/8193ce7e1e2ef23cd80efeb23df7ceca to your computer and use it in GitHub Desktop.
Reverse List
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 <stdint.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| struct list { | |
| struct list *next; | |
| int n; | |
| }; | |
| struct list *new_list(int *arr, size_t n) { | |
| struct list *ret = NULL, *ptr = NULL; | |
| for(size_t i = 0 ; i < n ; ++i) { | |
| if(ptr == NULL) { | |
| ptr = calloc(1, sizeof(struct list)); | |
| } else { | |
| ptr->next = calloc(1, sizeof(struct list)); | |
| ptr = ptr->next; | |
| } | |
| if(ret == NULL) { | |
| ret = ptr; | |
| } | |
| ptr->n = arr[i]; | |
| } | |
| return ret; | |
| } | |
| void delete_list(struct list *head) { | |
| for(struct list *it = head ; it != NULL ; ) { | |
| struct list *tmp = it->next; | |
| free(it); | |
| it = tmp; | |
| } | |
| } | |
| void print_list(struct list *head) { | |
| for(struct list *it = head ; it != NULL ; it = it->next) { | |
| printf("%d ", it->n); | |
| } | |
| } | |
| /* | |
| * @return reversed head | |
| */ | |
| struct list *reverse_list(struct list *head) { | |
| struct list *prev = NULL, *it = head; | |
| while(it != NULL) { | |
| struct list *tmp = it->next; | |
| it->next = prev; | |
| prev = it; | |
| it = tmp; | |
| } | |
| return prev; | |
| } | |
| int main(){ | |
| int arr[] = {1, 2, 3, 4, 5}; | |
| struct list *l = new_list(arr, sizeof(arr) / sizeof(*arr)); | |
| print_list(l); | |
| printf("\n"); | |
| l = reverse_list(l); | |
| print_list(l); | |
| printf("\n"); | |
| delete_list(l); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment