可扩展的数列排序

#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");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值