静态链表的创建,插入,删除操作

 

刚入门可以看http://t.csdnimg.cn/4P6XS

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

#define MaxSize 1000

typedef int Status;
typedef struct SNode{
	int data;
	int cur;
}StaticList[MaxSize+1]; 

Status LengthList(StaticList L);
Status MallocList(StaticList L);
void freeList(StaticList L,int e);

//明确这里有两个结点较为特殊:
//首先是第一个结点(数组下标为0的点);他不存放数据,他的cur用来记录备用链表的第一个结点的下标
//再是最后一个结点(数组下标为MaxSize)
//他的数据域也不存放数据,他的cur用来记录第一个有数据的结点的下标 


void Init(StaticList L)//初始化静态链表 
{
	for(int i=0;i<=MaxSize-1;i++)
	{
		L[i].cur=i+1;
	}
	L[MaxSize].cur=0;//将最后一个空闲结点置为0,表示指针置为NULL
	 
	L[MaxSize-1].cur=0;//因为一开始是空表,所以将它置为NULL,及直接赋值为0
						//如果不是空表的时候,这里将会记录第一个有数据元素的结点的下标 	
}


Status MallocList(StaticList L)//申请空间 
{
	int Cur=L[0].cur;
	if(Cur!=0)
	{
		L[0].cur=L[Cur].cur;
	}
	return Cur;
}


Status LengthList(StaticList L)//计算静态链表的长度(带有数据的) 
{
	int count=0;
	for(int i=L[MaxSize].cur;i!=0;i=L[i].cur)//这里的L[MaxSize].cur指向的是第一个有数据的元素 
	{
		count++;
	}
	return count;
}

//插入某元素 
bool InsertList(StaticList L,int pos,int e)
{
	if(pos<1||pos>LengthList(L)+1)//这里是插入到某个元素前面,所以可以插入到最后一个元素后面 
	return false;
	
	//这里要先申请一块空间
	int new_cur=MallocList(L);
	if(new_cur!=0)//如果为0,说明链表已经满了 
	{
		L[new_cur].data=e;
		//下面要调整游标
		int Cur=MaxSize;
		for(int i=1;i<=pos-1;i++)
		{
			Cur=L[Cur].cur;
		} 
		//实质上就是链表的插入 
		L[new_cur].cur=L[Cur].cur;
		L[Cur].cur=new_cur;
		return true;
	}
	return false;
}

//删除某元素 
bool DeleteList(StaticList L,int pos)
{
	if(pos<1||pos>LengthList(L))//这里是删除该元素 
	{
		return false;
	}
	
	int Cur=MaxSize;
	for(int i=1;i<=pos-1;i++)
	{
		Cur=L[Cur].cur;
	}
	int pos_cur=L[Cur].cur; 
	L[Cur].cur=L[pos_cur].cur;
	freeList(L,pos_cur);
	return true;
}

//释放空间 
void freeList(StaticList L,int e)
{
	L[e].cur=L[0].cur;
	L[0].cur=e;
} 

void PrintfList(StaticList L)
{
	for(int i=L[MaxSize].cur;i!=0;i=L[i].cur)
	{
		printf("%d ",L[i].data);
	}
	printf("\n");
}

int main(void)
{
	StaticList La;
	Init(La);
	InsertList(La,1,1);
	//这里第一个1代表的是插入的位置(插入在哪个位置前面)
	//这里的第二个1代表的是插入的数据是什么 
 
	
	InsertList(La,2,2);
	InsertList(La,3,3);
	InsertList(La,4,4);
	PrintfList(La);
	
	DeleteList(La,2);
	PrintfList(La); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值