#include <stdio.h>
#include <math.h>
int nodeNum = 5;//节点个数
const int radix = 10;//进制数
const int digit = 2;//最大位数
struct node *creatlist();
void print(struct node *head);
void removeAll(struct node *head);
struct node *selectSort(struct node *head);
struct node *radixSort(struct node *head);
int pow(int a, int b) {
int r = 1;
for (int i = 0; i < b; i++) {
r *= a;
}
return r;
}
struct node
{
int t;
node * link;
};
//建表
struct node *creatlist()
{
int i = 0;
int t;
struct node *head, *p, *q;
//头结点
scanf_s("%d", &t);
head = new struct node;
head->t = t;
head->link = 0;
q = head;
for (i = 0; i < nodeNum - 1; i++) {
scanf_s("%d", &t);
p = new struct node;
p->t = t;
p->link = 0;
q->link = p;
q = q->link;
}
return head;
}
//选择排序
struct node *selectSort(struct node *head)
{
if (head == 0) {
return false;
}
else {
struct node *p = head;
struct node *q = head;
struct node *min = head;
struct node *preq = head;
struct node *premin = head;
struct node *prep = head;
while (p->link != 0) {
preq = p;
q = p->link;
min = p;
while (q != 0) {
if (q->t < min->t) {
min = q;
premin = preq;
}
preq = q;
q = q->link;
}
if (p != min) {
if (p == head) {
head = min;
premin->link = min->link;
min->link = p;
prep = head;
}
else {//p不是头结点
premin->link = min->link;
min->link = p;
prep->link = min;
prep = min;
}
}
else {
prep = p;
p = p->link;
}
}
}
return head;
}
//基数排序
struct node *radixSort(struct node *head)
{
if (head == 0) {
return false;
}
struct node *tmp = 0, *p = head;
int i, j, di;
//建立桶
struct HeadNode
{
struct node *head, *tail;
};
HeadNode bucket[radix];
for (i = 0; i < radix; i++)
bucket[i].head = bucket[i].tail = 0;
for (i = 0; i < digit; i++) {
p = head;
while (p) {
//获取p->t当前位数
di = ((p->t) / (pow(10 , i))) % 10;
tmp = p;
p = p->link;
//插入di号桶尾,这里又采用尾插法
if (bucket[di].head == NULL) //无头节点、链表为空
bucket[di].head = bucket[di].tail = tmp;
else
{
bucket[di].tail->link = tmp; //原先的尾节点连接上新加入进来的节点
bucket[di].tail = tmp; //更新尾节点
}
}
//更新链表
head = 0;
for (j = radix-1; j >= 0; j--) {
if (bucket[j].head) //如果当前桶不为空
{
bucket[j].tail->link = head;
head = bucket[j].head; //更新表头
bucket[j].head = bucket[j].tail = NULL; //清空桶
}
}
}
return head;
}
//打印
void print(struct node *head)
{
if (head == 0) {
printf("这是个空表\n");
return;
}
struct node *tmp = head;
int i = 0;
while (i < nodeNum)
{
printf("%d ", tmp->t);
tmp = tmp->link;
i++;
}
printf("\n");
}
//释放
void removeAll(struct node *head)
{
struct node*p = head;
for (int i = 0; i < nodeNum; i++) {
p = head;
head = head->link;
delete p;
nodeNum = 0;
}
}
int main()
{
struct node *head1 = NULL;
struct node *head2 = NULL;
//创建链表
printf("输入5个值\n");
head1 = creatlist();
printf("输入5个值\n");
head2 = creatlist();
head1 = selectSort(head1);
head2 = radixSort(head2);
//打印单链表
printf("选择排序的链表为:\n");
print(head1);
printf("基数排序的链表为:\n");
print(head2);
//释放
removeAll(head1);
removeAll(head2);
return 0;
}
09-29
6792
11-24
989
05-30
278