数据结构(c语言实现)----------有序数组的插入

L是用户传入的一个线性表,函数Insert要将X插入Data[]中合适的位置,以保持结果依然有序。但如果X已经在Data[]中了,就不要插入,返回失败的标记0;如果插入成功,则返回true。另外,因为Data[]中最多只能存MAXSIZE个元素,所以如果插入新元素之前已经满了,也不要插入,而是返回失败的标记false。

题目参考自:https://pintia.cn/problem-sets/434/problems/965573204499779584
此答案仅供参考

代码展示

#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
#include<time.h>
#define MAXSIZE 10


typedef struct LNode {
	int Data[MAXSIZE];
	int Last; /* 保存线性表中最后一个元素的位置 */
}Node;

Node* ReadInput(); //初始化
void SortList(Node *l);//对顺序表进行排序
void printfList(Node *l);//遍历顺序表
int Search(Node *l, int x);//查找算法
bool insert(Node *l, int x);//插入操作
int main()
{
	Node *L;
	int X;
	int P;
	L = ReadInput();
	printfList(L);
	printf("输入需要插入的元素:");
	scanf("%d", &X);
	P = Search(L, X);
	if (P>0)
	{
		if (insert(L, X)) {
			printf("\n插入成功!\n");
		}
		else {
			printf("\n插入失败!\n");
		}
		
	}
	else {
		printf("该元素已经在表中\n");
	}
	printfList(L);
}
Node* ReadInput() {
	Node *l = (Node *)malloc(sizeof(Node));
	printf("输入数组的长度:");
	int len;
	scanf("%d", &len);
	if (len > MAXSIZE || l == NULL)
	{
		return NULL;
	}
	srand((int)time(0));
	l->Last = 0;
	for (int i = 0; i < len; i++)
	{
		l->Data[i] = rand() % 100 + 1;
		l->Last++;
	}
	//printf("%d\n", l->Last);
	SortList(l);
	return l;


}
void SortList(Node *l) {
//冒泡法排序
	int temp;
	for (int i = 0; i < l->Last - 1; i++)
	{
		for (int j = i; j < l->Last; j++)
		{
			if (l->Data[i] > l->Data[j])
			{
				temp = l->Data[j];
				l->Data[j] = l->Data[i];
				l->Data[i] = temp;
			}
		}
	}
}
void printfList(Node *l) {
	int i = 1;
	while (i <= l->Last)
	{
		printf("%d ", l->Data[i - 1]);
		i++;
	}
	printf("\n");
}
int Search(Node *l, int x) {
	int flag = 1;//元素是否存在的标志
	for (int i = 0; i < l->Last; i++)
	{
		if (l->Data[i]==x)
		{
			flag = 0;
			break;
		}
	}
	
	return flag;
}
bool insert(Node *l, int x) {
	if (l->Last==MAXSIZE)
	{
		return false;//判断顺序表是否是满的
	}
	l->Data[l->Last++] = x;
	SortList(l);
	return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何一平?

你的收获就是我学习的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值