forked from sysprog21/lab0-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shuffle.c
35 lines (30 loc) · 799 Bytes
/
shuffle.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdlib.h>
#include "list.h"
#include "shuffle.h"
void shuffle_swap(struct list_head *n1, struct list_head *n2)
{
struct list_head *tmp = n1->next;
n1->next = n2->next;
n2->next->prev = n1;
n2->next = tmp;
n2->next->prev = n2;
tmp = n2->prev;
n2->prev = n1->prev;
n1->prev->next = n2;
n1->prev = tmp;
n1->prev->next = n1;
}
void q_shuffle(struct list_head *head, size_t len)
{
if (!head || list_empty(head) || list_is_singular(head))
return;
struct list_head *tail = head->prev;
for (int i = len - 1; i > 0; i--) {
struct list_head *cur = head;
int j = rand() % (i + 1);
for (int tmp = 0; tmp <= j; tmp++)
cur = cur->next;
shuffle_swap(cur, tail);
tail = cur->prev;
}
}