花了点时间 #include <stdio.h>
#include <stdlib.h>
struct Number
{
int num;
struct Number *next;
};
void GetNumber(struct Number **ptr, int num);
void PrintNumbers(struct Number **ptr);
void FreeNumbers(struct Number **ptr);
int main()
{
int new_num;
char ch;
struct Number *ptr = NULL;
while(1)
{
printf("是否想存入数字(Y/N):");
do
{
scanf("%c", &ch);
fflush(stdin);
}while(ch != 'Y' && ch != 'N');
if(ch == 'Y')
{
printf("请输入数字:");
scanf("%d", &new_num);
GetNumber(&ptr, new_num);
}
else
{
break;
}
}
fflush(stdin);
if(ptr != NULL)
{
printf("是否想从小到大查看数字(Y/N):");
do
{
scanf("%c", &ch);
fflush(stdin);
}while(ch != 'Y' && ch != 'N');
if(ch == 'Y')
{
printf("您输入的数字从小到大排序是:\n");
PrintNumbers(&ptr);
}
FreeNumbers(&ptr);
}
printf("感谢您的使用,再见!\n");
return 0;
}
void GetNumber(struct Number **ptr, int num)
{
struct Number *temp = *ptr;
struct Number *previous = NULL;
struct Number *new1 = (struct Number *)malloc(sizeof(struct Number));
if(new1 == NULL) //判断申请内存是否成功
{
perror("malloc");
exit(-1);
}
new1->num = num;
if(*ptr == NULL) //此处判断ptr也就相当于判断了temp不为NULL,所以下一段中的while至少循环一次
{
*ptr = new1;
new1->next = NULL;
}
else
{
while(temp != NULL && temp->num < num)
{
previous = temp;
temp = temp->next;
}
if (previous == NULL) //只有一个节点,num小,头插.
{
*ptr = new1;
new1->next= temp;
}
else
{
if (previous->next == NULL) //最后一个节点
{
previous->next=new1;
new1->next=NULL;
}
else//中间插
{
previous->next=new1;
new1->next=temp;
}
}
}
}
void PrintNumbers(struct Number **ptr)
{
struct Number *temp = *ptr;
do
{
printf("%d\t", temp->num);
temp = temp->next;
} while(temp != NULL);
putchar('\n');
}
void FreeNumbers(struct Number **ptr)
{
struct Number *temp;
do
{
temp = *ptr;
*ptr = (*ptr)->next;
free(temp);
} while(*ptr != NULL);
}
|