数据结构 线性表的顺序表实现 c语言

线性表 的 顺序表 存储方式 实现,用的是c语言,实现增删改查功能。
参考的是 严蔚敏 的《数据结构》 (c语言版)

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


#define LIST_INIT_SIZE 100			//初始化顺序表长度
#define LISTINCREMENT 10			//每次增加的长度
#define ElemType int 						//定义数据类型 
#define Status bool							//定义返回值的类型

//定义类型
typedef struct{
	ElemType * elem;		//顺序表首地址
	int length;					//当前已用空间的长度
	int listSize;					//总空间大小
}SqList; 


//创建
Status InitList_sq(SqList &L){
	L.elem = (ElemType * )malloc(LIST_INIT_SIZE * sizeof(ElemType));
	if(! L.elem)return false;
	L.length = 0 ;
	L.listSize =  LIST_INIT_SIZE;
	return true;
} 

//print打印顺序表
void printList(SqList &L){
	printf("打印----------------------\n"); 
	for(int i=0; i<L.length; i++){
		printf("%d ", L.elem[i]);
	}
}

//插入
Status ListInsert_sq(SqList &L, int i, ElemType e){
	if(i<0 || i>L.length+1){		//判断插入位置是否合法
		return false;
	}
	if(L.length>=L.listSize){			//空间不够就扩容
		ElemType *	newbase = (ElemType * )realloc(L.elem, (L.listSize +LISTINCREMENT) * sizeof(ElemType));
		if(!newbase) return false;
		L.elem = newbase;
		L.listSize +=LISTINCREMENT; 
	}
	
	ElemType * p; ElemType * q;
	p = &L.elem[i-1];
	for(q=&(L.elem[L.length-1]); p<=q; q--){
		*(q+1) = *q; 
	}
	*p = e;
	L.length++;
} 

//删除
Status ListDelete_sq(SqList &L, int i, ElemType & e){
	if(i<1 || i>L.length){
		return false;
	}
	
	ElemType * p; 
	p = &(L.elem[i-1]);
	e =  * p;
	for(;p<&L.elem[L.length-1]; p++ ){
		*p = *p++;
	} 
	L.length--;
} 

//查找
Status ListFind_sq(SqList &L, int i, ElemType & e){
	if(i<1 || i>L.length){
		return false;
	}
	
	e = L.elem[i-1];
	return true;
	
	
} 

//更改 
Status ListUpdate_sq(SqList &L, int i, ElemType & e){
	if(i<1 || i>L.length){
		return false;
	}
	
	L.elem[i-1] = e;
	return true;
} 


int main(int argc, char** argv) {
	SqList sq ;
	InitList_sq(sq);
	ElemType e; 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值