|
|
发表于 2020-12-13 16:28:41
|
显示全部楼层
本楼为最佳答案
 - #include<stdio.h>
- #include<malloc.h>
- #include<stdlib.h>
- struct data{
- int n;
- struct data *next;
- };
- #define LEN sizeof(struct data)
- int m ;
- int N ; //全局变量,用来记录存放了多少数据。
- struct data * creat(void)//创建链表函数
- {
- struct data * head , * p1 , * p2 ;
- int d , k ;
- for(N = 0 , k = 0 ;; k ++ , N ++) {
- printf("Please enter a number(-1 for ending input) : ") ;
- scanf("%d" , & d) ;
- if(d != -1) {
- if((p2 = malloc(sizeof(struct data))) != NULL) {
- p2 -> n = d ;
- p2 -> next = NULL ;
- if(! k) head = p2 ;
- else p1 -> next = p2 ;
- p1 = p2 ;
- } else {
- fprintf(stderr , "\n") ;
- fprintf(stderr , "\tError : can't alloc memory !\n") ;
- fprintf(stderr , "\n") ;
- exit(1) ;
- }
- } else {
- break ;
- }
- printf("\n") ;
- }
- return head ;
- }
- void output(struct data * head)//定义打印输出链表函数
- {
- struct data * p ;
- for(p = head ; p ; p = p -> next) printf("%d\n" , p -> n) ;
- }
- struct data * sort(struct data * head)
- {
- struct data * h , * p , * q , * r , * t ;
- int f ;
- for(f = 1 , h = head ; f ;) {
- f = 0 ;
- for(r = NULL , q = h , p = q -> next ; q && p ; r = q , q = p , p = q -> next) {
- if(q -> n > p -> n) {
- t = p -> next ;
- p -> next = q ;
- q -> next = t ;
- if(r) {
- r -> next = p ;
- } else {
- h = p ;
- }
- f ++ ;
- }
- }
- }
- return h ;
- }
- int main()//主函数
- {
- int remove_n;//定义存放需要删除的数值的变量·
- struct data * stu , node;//声明结构指针变量
- stu = creat() ;//函数返回链表第一个节点的地址
- output(stu) ;//打印输出链表
- printf("\n");//换行
- stu = sort(stu);//排序
- printf("The result of ascending sorting:\n");
- output(stu);//升序输出
- }
复制代码
编译、运行实况
- D:\00.Excise\C>cl x.c
- 用于 x86 的 Microsoft (R) C/C++ 优化编译器 19.28.29334 版
- 版权所有(C) Microsoft Corporation。保留所有权利。
- x.c
- Microsoft (R) Incremental Linker Version 14.28.29334.0
- Copyright (C) Microsoft Corporation. All rights reserved.
- /out:x.exe
- x.obj
- D:\00.Excise\C>x
- Please enter a number(-1 for ending input) : 9
- Please enter a number(-1 for ending input) : 8
- Please enter a number(-1 for ending input) : 7
- Please enter a number(-1 for ending input) : 6
- Please enter a number(-1 for ending input) : 5
- Please enter a number(-1 for ending input) : 4
- Please enter a number(-1 for ending input) : 3
- Please enter a number(-1 for ending input) : 2
- Please enter a number(-1 for ending input) : 1
- Please enter a number(-1 for ending input) : -1
- 9
- 8
- 7
- 6
- 5
- 4
- 3
- 2
- 1
- The result of ascending sorting:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- D:\00.Excise\C>
复制代码 |
|