#include "stdio.h"
#include "malloc.h"
struct student{
int data;
struct student *next;
};
struct student *createList();
void printList(struct student *head);
struct student *createSortList();
void sortList(struct student *head);
main(){
struct student *head;
head=createList();
printList(head);
//head=createSortList(head);
//printList(head);
sortList(head);
printList(head);
}
struct student *createList(){
//创建链表
struct student *p;
struct student *q;
struct student *head;
int data;
head=(struct student *)malloc(sizeof(struct student));
head->next=NULL;
q=head;
scanf("%d",&data);
while(data!=0){
p=(struct student *)malloc(sizeof(struct student));
p->data=data;
p->next=q->next;
q->next=p;
q=q->next;
scanf("%d",&data);
}
return head;
}
struct student *createSortList(){
//创建有序链表
struct student *head;
struct student *p;
struct student *q;
struct student *preq;
int data;
head=(struct student *)malloc(sizeof(struct student));
head->next=NULL;
scanf("%d",&data);
while(data!=0){
p=(struct student *)malloc(sizeof(struct student));
p->data=data;
preq=head;
q=head->next;
while((q!=NULL)&&(q->data<p->data)){
q=q->next;
preq=preq->next;
}
p->next=preq->next;
preq->next=p;
scanf("%d",&data);
}
return head;
}
void sortList(struct student *head){
//从建好的链表中取数据,然后排序
struct student *p;
struct student *q;
struct student *tphead;
struct student *preq;
tphead=head->next;
head=(struct student *)malloc(sizeof(struct student));
head->next=NULL;
while(tphead!=NULL){
p=tphead;
tphead=tphead->next;
preq=head;
q=head->next;
while((q!=NULL)&&(q->data<p->data)){
q=q->next;
preq=preq->next;
}
p->next=preq->next;
preq->next=p;
}
}
void printList(struct student *head){
struct student *phead;
phead=head->next;
while(phead!=NULL){
printf("%4d",phead->data);
phead=phead->next;
}
printf("\n");
}
C语言实现sortList
最新推荐文章于 2024-06-23 15:32:54 发布