#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 10 //数值总数
#define STAGE 1 //每一个阶段的数量单位
#define stage MAX/STAGE+1
typedef struct node{
double upperlimit;
double lowerlimit;
struct node *right;
struct node *next;
}BNode,*LinkBucket;
double CreateRand(); //创建一个随机数 0-1
void CreateArray(double * array); //创建一个数组,存储随机数
int initBucketList(LinkBucket BList); //初始化一个链表
int CreateBucketList(LinkBucket L); //建立的阶段 分成的段数.
void printStrageList(LinkBucket L); //验证链表是否正常生成 与程序无关
int AddNumToRightList(double num,LinkBucket L) //使用 lowerlimit存储数据
{
LinkBucket p1 ,p2,p3;
p3 = p1 = p2 = (LinkBucket) malloc(sizeof(BNode));
initBucketList(p1);
initBucketList(p2);
initBucketList(p3);
p2 = L;
p1->lowerlimit = num;
if(p2->right == NULL)
{
p1->right = p2->right;
p2->right = p1;
return 1;
}
else
{
while(p2->right != NULL)
{
p3 = p2;
p2 = p2->right;
if( (p2->lowerlimit <= num ) && ( p2->right == NULL))
{
p1->right = p2->right;
p2->right = p1;
return 1;
}
if(p2->lowerlimit > num )
{
p1->right = p2;
p3->right = p1;
return 1;
}
if(p2->right->right != NULL && p2->right->right->lowerlimit > num)
{
p1->right = p2->right;
p2->right = p1;
return 1;
}
}
}
return 0 ;
}
int AddArrayToListBySort(double * array,LinkBucket L)
{
int i = 0;
while(i < stage )
{
LinkBucket p = (LinkBucket) malloc(sizeof(BNode));
initBucketList(p);
//LinkBucket p;
p = L;
int key = array[i] * 10; //得到整型值。
for(int j = 0 ; j <= key ; j++)
p = p->next;
AddNumToRightList(array[i],p);
i++;
}
return 1;
}
void Print(LinkBucket L)
{
LinkBucket p ;
p = (LinkBucket) malloc(sizeof(BNode));
initBucketList(p);
p = L->next;
while(p->next != NULL)
{
LinkBucket s ;
s = (LinkBucket) malloc(sizeof(BNode));
initBucketList(s);
s = p;
while(s->right != NULL)
{
s = s->right;
printf("%f ",s->lowerlimit);
}
p = p->next;
}
}
int main()
{
//printf("%f",CreateRand());
double array[MAX];
CreateArray(array);
LinkBucket L = (LinkBucket)malloc(sizeof(BNode));
initBucketList(L);
CreateBucketList(L);
printStrageList( L);
AddArrayToListBySort(array,L);
Print(L);
return 0;
}
double CreateRand()
{
return rand()%10000/10000.00;
}
void CreateArray(double * array)
{
srand((unsigned int)time(0));
int i = MAX ;
while(i >= 0)
{
array[i] = CreateRand();
printf("%d, %f\n",i,array[i]);
i--;
}
}
int initBucketList(LinkBucket BList) //初始化一个链表
{
BList->next = NULL;
BList->right = NULL;
BList->lowerlimit = 0.00;
BList->upperlimit = 0.00;
return 1;
}
int CreateBucketList(LinkBucket L) //建立的阶段 分成的段数.
{
LinkBucket p1,p2;
p1 = p2 =(LinkBucket) malloc(sizeof(BNode));
initBucketList(p1);
initBucketList(p2);
p2 = L;
for(int i = 0; i < stage ; i ++)
{
p1->lowerlimit = 0.1*i;
p1->upperlimit = 0.1*(i+1);
p1->next = p2->next;
p2->next = p1;
p2 = p1;
p1 =(LinkBucket) malloc(sizeof(BNode));
initBucketList(p1);
}
p2->next = NULL;
p2->right = NULL;
return 1;
}
void printStrageList(LinkBucket L) //验证链表是否正常生成 与程序无关
{
while(L->next!= NULL)
{
L = L->next;
printf("min=%f,max=%f\n",L->lowerlimit,L->upperlimit);
}
}