线性表的链式表示(静态链表)

线性表的链式表示(静态链表)

数据结构

typedef struct {
	char data;
	int next;
}SLinkList[MaxSize];

初始化,求表长

//初始化
void InitList(SLinkList* S) {
	S = (SLinkList*)malloc(sizeof(MaxSize));
	S[0]->next = -1;//0位置是头
}
//求表长
int Length(SLinkList S) {
	int ans = 0;
	int next = S[0].next;
	while (next>=0)
	{
		next = S[next].next;
		ans++;
	}
	return ans;
}

按序号查找

//按序号查找,并返回其所在的编号
int GetElem(SLinkList S, int i) {
	int next = S[0].next;
	while (next >= 0 && i > 1) {
		next = S[next].next;
		i--;
	}
	return next;
}

插入元素

//i位置插入e元素,原本i位置元素向后移
void ListInsert(SLinkList& S, int i, char e) {
	int p = GetElem(S, i);//i位置元素的编号
	//分配一个新内存
	int newItem = 1;
	while (S[newItem].data>0) {
		newItem++;
	}
	if (newItem == MaxSize - 1) {//超出内存限制
		printf("超出内存限制,不能继续添加!\n");
		return;
	}
	if (p<0)
	{
		if (i==1)
		{
			S[0].next = newItem;
			S[newItem].data = e;
			return;
		}
		else {
			printf("插入的位置出错!\n");
			return;
		}
	}
	int pre;
	if (i == 1) {
		pre = 0;
	}
	else {
		pre = GetElem(S, i - 1);//i-1位置的元素编号
	}
	S[pre].next = newItem;
	S[newItem].data = e;
	S[newItem].next = p;
}

删除元素

//删除元素,删除i位置的元素
char DeleteList(SLinkList& S, int i) {
	int p = GetElem(S, i);//i位置的编号
	if (p <= 0 || i <= 0) {
		printf("删除失败!\n"); return '\0';
	}
	int next = S[0].next;
	int pre;
	while (next != i) {
		pre = next;
		next = S[next].next;
		if (next < 0) {
			printf("删除失败!\n"); return '\0';
		}
	}
	S[pre].next = S[i].next;
	int ans = S[i].data;
	S[i].data = NULL;
	S[i].next = -1;
	return ans;
}

打印数组和链表

//打印数组
void PrintShu(SLinkList S) {
	int i = 1;
	printf("数组数据:0 ");
	while (i<MaxSize)
	{
		if (S[i].data > 0) {
			printf("%c ", S[i].data);
		}
		else {
			printf("0 ");
		}
		i++;
	}
	printf("\n");
}
//打印链表
void PrintList(SLinkList S) {
	printf("链表数据:");
	int next = S[0].next;
	printf("(0 0 %d)", next);
	while (next > 0) {
		printf("(%d %c %d)", next, S[next].data, S[next].next);
		next = S[next].next;
	}
	printf("\n");
}

测试

int main() {
	SLinkList S;
	InitList(&S);
	ListInsert(S, 1, 'a');
	PrintList(S);
	ListInsert(S, 1, 'b');
	PrintList(S);
	ListInsert(S, 2, 'c');
	PrintList(S);
	ListInsert(S, 1, 'd');
	PrintList(S);
	DeleteList(S, 2);
	PrintList(S);

	PrintShu(S);
	printf("表长:%d\n", Length(S));
	return 0;
}

在这里插入图片描述
在这里插入图片描述
大佬批评指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值