数据结构静态链表

//静态链表是用数组的方式实现链表的数据结构
#include <stdio.h>
#include <iostream>

using namespace std;

#define MAXSIZE 1000
#define OK 1
#define ERROR 0


typedef char ElemType;
typedef int Status;

	typedef struct
	{
	ElemType data;
	int cur;
	}StaticLinkList[MAXSIZE];


	Status InitList(StaticLinkList space)
	{
	//函数功能:初始化静态链表
	//1、数组0游标cur指向第一个备用空链表位
	//2、数组MAXSIZE-1游标cur指向链表第一个值
	//3、循环设置各个游标cur
	int i=0;
	for(i=0;i<MAXSIZE-1;i++)
	{
		space[i].cur=i+1;
	}
	
	space[MAXSIZE-1].cur=0;
	return OK;
	}

	int Malloc_SLL(StaticLinkList space)
	{
		//函数功能:分配空间,由于静态数组链表不能用指针,所以需要自己编写函数实现功能
		//1、返回数组标的cur就是第一个备用空链表的位置
		//2、设置数值0游标的cur为下一个备用空链表的位置,
		//空链表space[0].cur=1,下一个空链表的位置即space[1].cur=2
		int i;
		i=space[0].cur;
		if(space[0].cur)
			space[0].cur=space[i].cur;
		return i;
	
	}

	void Free_SLL(StaticLinkList space,int k)
	{
		//函数功能:释放空间.
		//1、设置k的游标为0的游标
		//2、设置数组0游标的cur值为删除的链表结点位置
		space[k].cur=space[0].cur;
		space[0].cur=k;
	}

	int Len_SLL(StaticLinkList space)
	{
	//函数功能:返回链表长度
		int i,c=0;
		i=space[MAXSIZE-1].cur;
		while(i)
		{
		i=space[i].cur;
		c++;
		}
		return c;		
	}

	Status InsertList(StaticLinkList space,int i,ElemType e)
	{
	//函数功能:插入链表数据
	//1、查找要插入位置
	//2、分配空间
	//3、插入数据
		int j,k,l;
		k=MAXSIZE-1;
		if(i<1||i>Len_SLL(space)+1)
			return ERROR;
		j=Malloc_SLL(space);
			if(j)
			{
				space[j].data=e;

				for(l=1;l<=i-1;l++)
					k=space[k].cur;
				space[j].cur=space[k].cur;
				space[k].cur=j;
				return OK;
			}
			return ERROR;
	}

	Status DeleteList(StaticLinkList space,int i)
	{
	//查找要删除的位置,位置为游标 i要减去1 从链表尾部获取第一个数据游标,依次遍历
	//删除数据
	//收回空间
		int j,kb,k;
		k=space[MAXSIZE-1].cur;
		for(j=1;j<i-1;j++)
		{
			kb=space[k].cur;
		}
		k=space[kb].cur;
		space[0].cur=k;//设置数组0为要删除元素位置
		               //要删除元素的前一个元素的游标设置为删除元素的下一个元素
		space[kb].cur=space[k].cur;
		               //释放删除元素空间

		return OK;
	}

	Status PrintList(StaticLinkList space)
	{
		int l,i,j;
		l=Len_SLL(space);
		j=space[MAXSIZE-1].cur;
		for(i=1;i<=l;i++)
		{
			cout<<space[j].data<<endl;
			j=space[j].cur;
		}
		return OK;
	}
	


int main()
{
	StaticLinkList l;
	int len=0,i;
	InitList(l);

	InsertList(l,1,'a');
	InsertList(l,2,'b');
	InsertList(l,3,'c');
	InsertList(l,4,'d');
	InsertList(l,5,'e');
	InsertList(l,6,'f');
	PrintList(l);
	cout<<"-----"<<endl;
	DeleteList(l,3);
	PrintList(l);

	cout<<"-----"<<endl;
	DeleteList(l,5);
	PrintList(l);
	cout<<"-----"<<endl;
	InsertList(l,2,'f');
	PrintList(l);

	len=Len_SLL(l);
	cout<<"链表长度为:"<<len<<endl;
	system("pause");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值