6-6-2.c

来自「2005软件工程师考试下午编程题源代码」· C语言 代码 · 共 57 行

C
57
字号
/*中国系统分析员顾问团,http://www.csai.cn*/
/*程序员下午考试指南书籍源码*/

#include <stdio.h>
#include <stdlib.h>
struct node{
int value;
struct node *next;
};

struct node *create(int a[], int n){
struct node *h, *q;
for(h=NULL;n;n--){
q = ( struct node *)malloc(sizeof(struct node ));
q -> value = *a++;
q->next = h;
h = q;
}
return h;
}

void sort( struct node **h ){
struct node *p,*q,*r,*s,*hl;
hl = p = ( struct node*)malloc(sizeof(struct node ));
p->next = *h;
while( p->next != NULL ){
q = p->next;
r = p;
while( q->next != NULL ){
if ( q->next->value <r->next->value )
r = q;
q = q->next;
}
if( r != p ){
s = r->next;
r->next = s->next;
s->next = p->next;
p->next = s;
}
p = p->next;
}
*h = hl->next;
free(hl);
}

int test_data[] = {5,9,3,4,5,7,8};

main(){
struct node *h, *p;
h = create(test_data,sizeof(test_data)/sizeof(test_data[0]));
for(p = h; p; p = p->next) printf("%5d",p->value);
printf("\n");
sort(&h);
for(p = h; p; p = p->next) printf("%5d",p->value);
printf("\n");
}

⌨️ 快捷键说明

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