Created
October 12, 2025 15:13
-
-
Save coderodde/672c332adb7935661d6f7768bb095803 to your computer and use it in GitHub Desktop.
Splitting a linked list into odd and even sublists.
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 <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct list_node_t { | |
int datum; | |
struct list_node_t* next; | |
} list_node_t; | |
typedef struct list_t { | |
list_node_t* head; | |
list_node_t* tail; | |
size_t size; | |
} list_t; | |
bool list_t_init(list_t* list) { | |
if (list == NULL) { | |
return false; | |
} | |
list->head = NULL; | |
list->tail = NULL; | |
list->size = 0; | |
return true; | |
} | |
bool list_t_append(list_t* list, int datum) { | |
if (list == NULL) { | |
return false; | |
} | |
list_node_t* new_node = malloc(sizeof *new_node); | |
if (new_node == NULL) { | |
return false; | |
} | |
new_node->datum = datum; | |
new_node->next = NULL; | |
if (list->head == NULL) { | |
list->head = new_node; | |
list->tail = new_node; | |
} else { | |
list->tail->next = new_node; | |
list->tail = new_node; | |
} | |
list->size++; | |
return true; | |
} | |
bool list_t_split_odd_even(const list_t* list, | |
list_t* odd, | |
list_t* even) { | |
if (list == NULL || odd == NULL || even == NULL) { | |
return false; | |
} | |
if (odd->size != 0 || even->size != 0) { | |
return false; | |
} | |
list_node_t* current = list->head; | |
size_t counter = 1; | |
while (current != NULL) { | |
if (counter % 2 == 1) { | |
list_t_append(odd, current->datum); | |
} else { | |
list_t_append(even, current->datum); | |
} | |
++counter; | |
current = current->next; | |
} | |
return true; | |
} | |
void list_t_print(list_t* list) { | |
if (list == NULL) { | |
printf("NULL"); | |
return; | |
} | |
bool first = true; | |
for (list_node_t* node = list->head; node != NULL; node = node->next) { | |
if (first) { | |
first = false; | |
} | |
else { | |
printf(" "); | |
} | |
printf("%d", node->datum); | |
} | |
} | |
int main() | |
{ | |
list_t list; | |
list_t_init(&list); | |
for (int datum = 1; datum < 10; ++datum) { | |
list_t_append(&list, datum); | |
} | |
puts("Source list:"); | |
list_t_print(&list); | |
puts(""); | |
list_t odd_list; | |
list_t even_list; | |
list_t_init(&odd_list); | |
list_t_init(&even_list); | |
list_t_split_odd_even(&list, &odd_list, &even_list); | |
puts("Odd list:"); | |
list_t_print(&odd_list); | |
puts(""); | |
puts("Even list:"); | |
list_t_print(&even_list); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment