您的位置:首页 > 其它

[ --> C Language<-- ] 随机数链表排序

2006-12-18 13:36 183 查看
// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct node{
int key;
node *next;
};

void printChain(node *head){
node *p=head->next;
while(p!=NULL){
printf("%d/n",p->key);
p=p->next;
}
}

void composeChain(node *head, node *narray[],int pos){
int mol;
int denominator;
switch(pos){
case 0:
mol=10;
denominator=1;
break;
case 1:
mol=100;
denominator=10;
break;
case 2:
mol=1000;
denominator=100;
break;
default:
mol=0;
}

//split chain
node *p=head->next;
int index;
node *q;
while(p!=NULL){
index=(p->key%mol)/denominator;
q=narray[index];
while(q->next!=NULL){
q=q->next;
}
q->next=p;
q=p;
p=p->next;
q->next=NULL;
}

//combine chain
p=head;
for(int i=0;i<10;i++){
// printf("Array[%d]: %s/n",i,&"********");
// printChain(narray[i]);

node *branch=narray[i]->next;
if(branch!=NULL){
p->next=branch;
}
node *lastN=NULL;
while(branch!=NULL){
lastN=branch;
branch=branch->next;
}
if(lastN!=NULL){
p=lastN;
}
narray[i]->next=NULL;
}
}

void main(){
int i;
node *head=(node *)malloc(sizeof(node));

//init chain
node *p=head;
time_t t;
srand((unsigned)time(&t));
for(i=0;i<10;i++){
node *n=(node *)malloc(sizeof(node));
n->key=int(rand()%1000);
n->next=NULL;
p->next=n;
p=n;
}

node *narray[10];
for(i=0;i<10;i++){
narray[i]=(node *)malloc(sizeof(node));
narray[i]->next=NULL;
}

printf("Init chain:/n");
printChain(head);

for(i=0;i<3;i++){
composeChain(head, narray,i);
// printf("%s%d:/n",&"###### ",i);
// printChain(head);

}

//print the chain
printf("/nSorted chain:/n");
printChain(head);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: