我一直在做一个项目。部分项目需要一个混洗链表。这个函数是fisher-yates shuffle算法的一个实现。它将链表放入一个数组中。然后它洗牌。然后重新链接它。
经过一些测试,我发现有时当我对链表进行洗牌时,我会在某处丢失一个节点。我用 ubsan 和 asan 做了一些测试。他们都没有表现出任何东西。我曾经遇到过这个函数的问题,后来导致了段错误。段错误是由于未正确重新链接链表而引起的。更具体地说,链表中改组之前的最后一个节点未正确重新链接。我通过在改组之前使列表循环来解决这个问题。
以下是用于混洗以及交换和重新链接功能的代码:
linked_node* shuffle(linked_node* head) {
int count = 0;
linked_node* count_head = head;
while (count_head != NULL) {
count++;
count_head = count_head->next;
}
#ifdef DEBUG
fprintf(stderr, "count: %i\r\n", count);
#endif
linked_node** array = malloc(count * sizeof(linked_node*));
int i = 0;
linked_node* add_head = head;
for (i = 0; i < count; i++) {
array[i] = add_head;
add_head = add_head->next;
}
//made circluar to prevent segfault with the last node
array[count - 1]->next = head;
srand48(time(NULL));
for (int j = count - 1; j > 0; j--) {
int random = lrand48() % (j+1);
array_swap(&array[j], &array[random]);
}
for (int k = 0; k > count - 1; k++) {
relink(array[k], array[k + 1]);
}
linked_node* new_head = array[0];
//made circular for ease of use later
array[count - 1]->next = new_head;
free(array);
return new_head;
}
static inline void relink(linked_node* prev, linked_node* next) {
if (prev != NULL && next != NULL) {
prev->next = next;
}
}
void array_swap(linked_node** a, linked_node** b) {
linked_node* temp = *a;
*a = *b;
*b = temp;
}