可扩展的数列排序

来源:互联网 发布:朗读文字的软件 编辑:程序博客网 时间:2024/05/21 20:21
#include<stdio.h>#include<malloc.h>/*问题描述:从键盘输入任意个整数,以0作为结束标志。对这个整数序列进行排序并输出排序后的结果。问题分析:题目要求从键盘输入任意个整数,因此在数据的组织上就不能使用数组了。因为数组的内存分配是在编译时完成的,即在编写代码时就指定数组的大小。          从键盘输入任意个整数,就是说要分配的内存空间的大小是不固定的,需要在程序执行时根据实际输入的整数个数来分配内存空间,所以考虑使用链表的  方式来组织数据。*/struct node{int data;struct node *next;};struct node *CreateLink();void BubbleSort(struct node *head);void Print(struct node *head);int main(void){struct node *head;head=CreateLink();BubbleSort(head);printf("排序后的结果为:\n");    Print(head);return 0;}struct node *CreateLink(){struct node *head,*p,*q;int n;  head=(struct node *)malloc(sizeof(struct node));p=head;printf("请输入要排序的整数序列,并以0作为结束标志:\n");scanf("%d",&n);while(n){q=(struct node *)malloc(sizeof(struct node));q->data=n;p->next=q;p=q;scanf("%d",&n);}p->next=NULL;head=head->next;return head;}void BubbleSort(struct node *head){struct node *p=head;int count=0,i,j,temp;while(p){count++;p=p->next;}for(i=0;i<count-1;i++){  p=head;for(j=0;j<count-i-1;j++){if(p->data>p->next->data){temp=p->data ;p->data=p->next->data;p->next->data=temp;}p=p->next ;}}}void Print(struct node *head){struct node *p=head;if(!p) printf("链表为空");else while(p){printf("%d ",p->data );p=p->next;}printf("\n");}

原创粉丝点击