编写一个C程序,实现这样的功能,从键盘输入任意个整数,以0作为结束标志,对这个数列从小到大排序。并输出结果。
首先让我们想到的动态数列,我们最好就是使用链表存储数据了。然后使用冒泡排序对链表进行排序操作。代码如下:
- #include <string.h>
- #include <stdio.h>
- typedef int ElemType;
- typedef struct node{
- ElemType data;
- struct node *next;
- } LNode, *LinkList;
- LinkList GreatLinkList(int n)
- {
- LinkList p,r,list = NULL;
- ElemType e;
- int i;
-
- for(i = 1; i <= n; i++){
- scanf("%d",&e);
- p=(LinkList)malloc(sizeof(LNode));
- p->data = e;
- p->next = NULL;
- if(!list)
- list = p;
- else
- r->next = p;
-
- r = p;
- }
- return list;
- }
- void insertList(LinkList *list, LinkList q, ElemType e)
- {
- LinkList p;
- p = (LinkList)malloc(sizeof(LNode));
- p->data = e;
- if(!*list){
- *list = p;
- p->next = NULL;
- }
- else{
- p->next = q->next;
- q->next = p;
- }
- }
- void Sort(LinkList q)
- {
- LNode *p = q;
- int t,i,j,k=0;
- while(p){
- k++;
- p = p->next;
- }
- p = q;
- for(i=0; i<k-1; i++){
- for(j=0; j<k-i-1; j++){
- if(p->data > p->next->data){
- t = p->data;
- p->data = p->next->data;
- p->next->data = t;
- }
- p = p->next;
- }
- p = q;
- }
- }
- void Print(LinkList q)
- {
- while(q){
- printf("%d ",q->data);
- q = q->next;
- }
- }
- int main(int argc, char* argv[])
- {
- ElemType e;
- LinkList l,q;
- printf("please input some integer digit and type 0 for end\n");
- q = l = GreatLinkList(1);
- scanf("%d",&e);
- while(e){
- insertList(&l,q,e);
- q = q->next;
- scanf("%d",&e);
- }
-
- Sort(l);
- Print(l);
- return 0;
- }
程序编译,执行结果
E:\src\c\miaoqu>gcc 7.2.c
gcc 7.2.c
E:\src\c\miaoqu>a.exe
a.exe
4 32 4 5 6 7 8 0
please input some integer digit and type 0 for end
4 4 5 6 7 8 32
阅读(3222) | 评论(0) | 转发(0) |