单链表——对输入数字排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//输入若干个数字,进行排序输出
struct NUM{
int num;
struct NUM *next;
};
void getnum(struct NUM **head){
struct NUM *a,*temp,*point,*prepoint;
a=(struct NUM*)malloc(sizeof(struct NUM));
if(a==NULL){
printf("内存分配失败\n");
}
printf("请输入数字\n");
scanf("%d",&(a->num));
if(*head==NULL){
a->next=NULL;
*head=a;
}
else{
point=*head;
if(point->num>=a->num){
temp=*head;
*head=a;
a->next=temp;
}
else{
do{
prepoint=point;
point=point->next;
if(point==NULL){
prepoint->next=a;
a->next=NULL;
break;
}
else{
if(((point->num)>=(a->num))&&((prepoint->num)<(a->num))){
temp=prepoint->next;
prepoint->next=a;
a->next=temp;
break;
}
}
}while(1);
}
}
}
void printnum(struct NUM *head){
struct NUM *temp;
temp=head;
while(temp!=NULL){
printf("%d ",temp->num);
temp=temp->next;
}
printf("\n");
}
int main(void){
char ch;
struct NUM *head=NULL;
while(1){
printf("是否需要输入数字(Y/N)\n");
do{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y'){
getnum(&head);
}
printf("是否需要打印数字(Y/N)\n");
do{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y'){
printnum(head);
}
}
return 0;
}