你的代码似乎不能完成链表排序。给你写一个选择法排序的供参考——
#include "stdio.h"
#include
struct student{//结构体数据域
char name[10];
double score;
char num[10];
};
struct node{//结构体的结构体
struct student data;//数据域
struct node *next;//指针域
};
struct node *sort(struct node *head){//排序函数
struct node *p,*q,*t;
struct student x;
for(p=head;p;p=p->next){
for(t=p,q=t->next;q;q=q->next)
if(strcmp(t->data.num,q->data.num)==1)
t=q;
if(t-p)
x=p->data,p->data=t->data,t->data=x;
}
return head;
}
int main(int argc,char *argv[]){//测试主函数
struct node A[5]={{"AAA",68.9,"10101",&A[1]},{"BBB",88.3,"13101",&A[2]},
{"CCC",78.0,"11109",&A[3]},{"DDD",88.1,"19141",&A[4]},
{"EEE",99.5,"10008",NULL}};//模拟了个长度为5的无头链表
int i;
printf("Before ordering:\n");
for(i=0;i<5;i++)
printf("%s: %s\t%.2f\n",A[i].data.name,A[i].data.num,A[i].data.score);
sort(A);//调用自定义排序函数
printf("\nAfter ordering:\n");
for(i=0;i<5;i++)
printf("%s: %s\t%.2f\n",A[i].data.name,A[i].data.num,A[i].data.score);
return 0;
}
运行样例:
#include
#include
typedef struct node{
int value;
struct node *link;
} NODE;
void insert(NODE**,int);
void print(NODE*);
void free_node(NODE*);
NODE* creat(int);
int main(void){
NODE *header=NULL;
int value;
printf("Input values separated by space:\n");
while(scanf("%d",&value)){
insert(&header,value);
if(getchar()=='\n') break;
}
printf("Here are the values in sort:\n");
print(header);
free_node(header);
return 0;
}
void insert(NODE **header_p,int value){
NODE *current,*previous,*new;
new=creat(value);
previous=NULL;
current=*header_p;
while(current!=NULL&¤t->valueprevious=current;
current=current->link;
}
if(current==*header_p){
*header_p=new;
new->link=current;
}else if(current==NULL){
previous->link=new;
new->link=current;
}else{
previous->link=new;
new->link=current;
}
}
void print(NODE *header){
NODE *current;
current=header;
while(current != NULL){
printf("%d ",current->value);
current=current->link;
}
}
void free_node(NODE *header){
NODE *current,*next;
current=header;
while(current->link != NULL){
next=current->link;
free(current);
current=next;
}
free(current);
}
NODE* creat(int value){
NODE *new;
new=(NODE *)malloc(sizeof(NODE));
new->value=value;
return new;
}
LinkList Sort(LinkList SL)/*递增排序函数:入口参数:链表的头指针,此为链表中的排序函数*/
{
LinkList p,q;
int temp;
for(p=SL;p!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->data>q->data)
{
temp=q->data;
q->data=p->data;
p->data=temp;
}
}
}
return SL;
}
如题按NUM排序,所以没有交换节点,只交换了数据,本质就是冒泡排序
如果交换节点在判断内就是
LinkList Sort(LinkList SL)/*递增排序函数:入口参数:链表的头指针,此为链表中的排序函数*/
{
LinkList p,q,s;
int temp;
s = SL
for(p=SL;p!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->data>q->data)
{
p->next = q->next;
q->next = p;
s->next = q;
p = q;
}
}
if(s=SL){
SL = s;
s = p;
}else {
s = P;
}
}
return SL;
}
(网上粘贴,难得写了)