ZJGSU 1737 链表

题目描述

请根据输入数据构造一个带头结点的单链表,链表结点的数据结构为struct node {int data; struct node *next;},试设计算法:按递增次序输出单链表中各结点的数据元素,并释放结点所占用的存储空间。

要求:不允许使用数组作为辅助存储空间。

输入

每组测试数据包括两行,第一行为单链表中的元素个数n;第二行为n个元素的值。

输出

排序后的元素值,每组测试数据输出占一行,行末无空格。

样例输入

6 4 5 9 3 2 1

样例输出

1 2 3 4 5 9

#include<stdio.h>
#include<stdlib.h>
struct node {
	int data;
	struct node *next;
};
void Insert(struct node*p,int i,int a)//插入新元素(尾插)
{
	while(p->next)
	{
		p=p->next;
	}
	struct node ss;
	struct node *s;//每新加一个元素就要申请一块新的内存来存储新元素
	s=(struct node*)malloc(sizeof(ss));//然后再把它连接到原先的链表当中
	s->data=a;
	s->next=NULL;
	p->next=s;
}
int main()
{
	int n;
	scanf("%d",&n);
	struct node *p;
	struct node nn;
	p=(struct node*)malloc(sizeof(nn));
	if(p==NULL)return -1;
	p->next=NULL;//初始化头指针
	for(int i=0;i<n;i++)
	{
		int a;
		scanf("%d",&a);
		Insert(p,i,a);//每输入一个元素,插入一次
	}
	struct node*tail=p;
	while(tail!=NULL)tail=tail->next;
	for(int i=0;i<n;i++)//冒泡排序
	{
		struct node*curr=p->next;
		struct node*pre=p;
		for(int j=0;j<n-1;j++)
		{
			if(curr->data>curr->next->data)
			{
				struct node*q=curr->next->next;
				pre->next=curr->next;
				curr->next->next=curr;
				curr->next=q;
				if(curr->next==tail)tail=curr;//尾指针特判
			}
			pre=pre->next;
			curr=pre->next;
		}
	}
	p=p->next;
	while(p->next)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("%d",p->data);//这里是怕行末无空格,所以最后一个元素分开输出了
	free(p);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值