实现顺序表的基本运算功能

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

#define MAX 100 
typedef char ElemType;
typedef struct
{
	ElemType data[MAX];
	int length ;
}SqList;             //构建结构体


int CreateList(SqList *L, ElemType a[], int n)
{
	int i = 0, k = 0;
	L = (SqList *)malloc(sizeof(SqList));
	while(i<n)
	{
		L -> data[k] = a[i];
		k++;
		i++;
	}
	L -> length = k;
}                     //尾插法,可省略此函数,直接用ListInsert函数进行插入操作




int InitList(SqList *L)
{
	L = (SqList *)malloc(sizeof(SqList));
	L -> length = 0;
}

//初始化顺序表


int ListInsert(SqList *L, int i, ElemType e)
{
	int k;
	for(k = L -> length; k > i; k -- )
		L -> data[k] = L -> data[k-1];
	L -> data[i] = e;
	L -> length ++;
}  //在顺序表中第i个位置插入元素e

int DispList(SqList *L, int n)
{
	for(int i = 0; i < n; i++)
	printf("%c ", L -> data[i]);
	printf("\n");
}   //打印顺序表的内容 ,可以由用户自定义打印顺序表的前n项 


int ListLength(SqList *L)
{
	printf("此顺序表的长度:%d\n\n", L -> length + 1);
} //输出顺序表的长度 

int ListEmpty(SqList *L)
{
	if(L -> length == 0)
		printf("此顺序表为空\n\n");
	else
	 	printf("此顺序表不为空\n\n");
} //判断此顺序表是否为空 

int GetElem(SqList *L, int i)
{
	
	ElemType e = L -> data[i-1];
	printf("此顺序表的第%d个元素是:%c\n\n",i,e);
}
//输出顺序表第n个元素值

int LocateElem(SqList *L, ElemType e)
{
	int i = 0;
	while(i<L -> length && L -> data[i]!= e)
		i++;
		printf("%c的位置是第%d个\n\n", e , i+1);
}   //打印顺序表中某个元素的位置 

int ListDelete(SqList *L, int i) 
{
	for(int j = i-1 ; j < L-> length; j++)
		L -> data[j] = L -> data[j+1];
}  //删除顺序表的第i个位置的元素 

int DestriyList(SqList *L)
{
	free(L);
} //释放顺序表L 

int main( ) {
	
	SqList L;	//新建顺序表L 
	InitList(&L);	//初始化顺序表L 
	
	printf("依次在顺序表中插入“a , b , c , d , e ”\n");
	ListInsert(&L , 0 , 'a');	 
	ListInsert(&L , 1 , 'b');
	ListInsert(&L , 2 , 'c');	//ListInsert为在第i个位置插入元素e 
	ListInsert(&L , 3 , 'd');
	ListInsert(&L , 4 , 'e');
	
	DispList(&L , 5);			//打印顺序表的前5项 
	
	ListLength(&L);			// 输出顺序表的长度
	
	ListEmpty(&L); 					//判断此顺序表是否为空 
	
	GetElem(&L,3);			//输出顺序表的第3个元素值 
	
	LocateElem(&L , 'a');   //打印某个元素的位置 
	
	ListInsert(&L , 3 , 'f');
		DispList(&L , 6);	//在顺序表的第4个位置上插入f,然后将顺序表的前6项打印出来 
		
	ListDelete(&L,3); 
	DispList(&L , 6);		//删除顺序表的第3个元素,然后再将前6个元素打印出啦 
	
	DestriyList(&L); 		//释放顺序表 
}

此练习仅作为李春葆《数据结构》第2章线性表下的顺序表实现基本运算

其中一部分运算没有完全按照实验要求进行,不够严谨,会有些许的错误,待作者有空时会加以修改

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值