【C真题】键盘读入整数,并按从小到大的顺序输出输入整数中互不相等的那些整数。

【测试数据】这里为了方便,采用用文件读入方式

4 5 2 1 3 3 2 4 7

【代码】

#include <stdio.h>
#include <stdlib.h>

typedef struct LNode
{
	int data;
	struct LNode* next;
}LNode;

//采用直接插入法排序,且与序列中值相等的元素不重复插入
void InsertSort(LNode* L, int x)
{
	LNode* p, *s;
	p = L;

	//创建一个结点s
	s = (LNode*)malloc(sizeof(LNode));
	s->data = x;
	s->next = NULL;

	//找到刚好比x大的结点,该结点可能大于x,也可能等于x
	while (p->next != NULL && p->next->data < x)
	{
		p = p->next;
	}

	//找不到比x大的结点,x可以之间插在链表后面
	if (p->next == NULL)
	{
		p->next = s;
	}
	else if(p->next->data > x)
	{
		s->next = p->next;
		p->next = s;
	}
	//如果找到的结点与x相等则什么都不做

}


LNode* CreateList()
{
	LNode* L;
	int x;

	FILE* fp;

	if ((fp = fopen("data.txt", "r")) == NULL)
	{
		exit(0);
	}

	//构建一个头结点
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;

	while (fscanf(fp, "%d", &x) != EOF)
	{
		InsertSort(L, x);
	}

	return L;
}

void PrintList(LNode* L)
{
	LNode* p;

	p = L->next;

	while (p)
	{
		printf("%d ", p->data);
		p = p->next;
	}
}

int main()
{
	LNode* L;

	L = CreateList();

	PrintList(L);

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值