线性表(c)

#include<stdio.h>
#include<stdlib.h>
 
#define MAX_SIZE 100
#define SIZE 20
 
 typedef int ElemType;

typedef struct{
	ElemType *elem;
	ElemType size;
	ElemType count;
}SqList; 
 
ElemType InitList(SqList *L)             //初始化线性表               
{
	L->elem =(int *)malloc(MAX_SIZE*sizeof(int));
	L->count = 0;
	L->size = 100;
	return 0;
}
 
ElemType InsertList(SqList *L, ElemType pos, ElemType elem)   //往线性表位置为pos插入元素elem
{
	if(pos<1 || pos > L->count+1)
	{
		return 0;
	}
	if(L->count == L->size)
	{
		ElemType *p = (ElemType *)realloc(L->elem ,(L->size+SIZE)*sizeof(ElemType)); 
		if(p == NULL)
		{
			return -1;
		}
		L->elem = p; 
		L->size += SIZE;
	}
	for(ElemType i=L->count-1;i>=pos-1;i--)
	{
		L->elem[i+1]=L->elem[i];
	}
	L->elem[pos-1]=elem;
	L->count +=1;
	return 0;
}

ElemType DeleteList(SqList *L, ElemType pos)  //删除线性表中位置为pos的元素elem
{
	if(pos<1 || pos>L->count)
	{
		return 0;
	}

	for(int i=pos; i <= L->count; i++)
	{
		L->elem[i-1]=L->elem[i]; 
	}
	L->count --;
	return 0;
} 

ElemType LocateList(SqList L,ElemType elem)                //获取元素elem在线性表中L中的位置
{
	ElemType i;
	for(i=0;i<=L.count-1;i++)
	{
		if(L.elem[i]==elem)
		{
			return i+1;
	    }
    }
    return 0;
}

ElemType PrintList(SqList L)                      //打印线性表
{
	for(ElemType i=0;i<L.count ;i++)
	{
		printf("L.elem[%d] = %d\n", i+1, L.elem[i]);
	}
	printf("\n");
	return 0;
}
ElemType main()
{
	SqList L;
	InitList(&L);

	// InsertList(&L, 1, 3);
	// InsertList(&L, 2, 4);
	// InsertList(&L, 3, 5);
	// InsertList(&L, 4, 6);
	// InsertList(&L, 5, 2);
	// InsertList(&L, 99, 2);
	for(ElemType i = 0; i<=10; i++)
	{
		InsertList(&L, i, i+1);
	}
	PrintList(L);
	// printf("L:\n%d\n", L.count);
	// printf("\n%d\n", LocateList(L, 2));
	DeleteList(&L, 8);
	PrintList(L);

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

trust Tomorrow

感谢支持!

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

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

打赏作者

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

抵扣说明:

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

余额充值