shuffle.c

来自「自己做的常用库和实现的数据结构。public domain.」· C语言 代码 · 共 84 行

C
84
字号
/* Demo of my guess of Mplayer's -shuffle argv. * * Written by Cyril Hu (cyrilhu@gmail.com), public domain. */#include<stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>#define MAX 80#define N 10typedef struct plink {	char *data;	struct plink *next;} PL;PL *head, *t;void destroy(PL *p){	PL *t;	while(p) {		p = p->next;		free(p);		free(p->data);		p = t;	}}void disp(PL *p){	puts("");	while(p) {		printf("%s", p->data);		p = p->next;	}}PL *mvlink(PL *p, size_t n){	size_t i;	for(i=1; i<n && p; i++,p=p->next);	return p;}void swap(PL *a, PL *b){	char *t = a->data; a->data = b->data; b->data = t;}void add_to_link(const char *src, size_t len, size_t cnt){	PL *p;	char *dst;	p = (PL *)malloc(sizeof(PL));        dst = (char *)calloc(len, sizeof(char));	if(!p || !dst) {		fprintf(stderr, "Fatal: mem alloc failed");		exit(EXIT_FAILURE);	}	strcpy(dst, src);	p->data = dst;	if(cnt == 1) 		head = t = p;	else {		t->next = p;		t = p;	}	t->next = NULL;}int main(void){	char buf[MAX];	size_t i, j, cnt = 0;	for(i=0; i<N; ++i) {		fgets(buf, sizeof(buf), stdin);		add_to_link(buf, strlen(buf), ++cnt);	}	srand(time(NULL));	for(i=1; i<=cnt; i++) {		j = 1 + (size_t )( (double)cnt * rand() / ( (RAND_MAX) + 1.0));		swap(mvlink(head, i), mvlink(head, j));	}	disp(head);	destroy(head);	return EXIT_SUCCESS;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?