3.2.3 线性表的链式存储实现

定义结点结构

typedef struct LNode *PtrToLNode;
struct LNode
{
	ElementType Data;
	PtrToLNode Next;
};
typedef PtrToLNode Position; /*结点的地址?*/ 
typedef PtrToLNode List;
List L;

1.求表长

int Length(List L)
{
	Position p;
	int cnt=0;
	p=L;    /*p指向表的第一个结点*/ 
	while(p)
	{
		p=p->Next;
		cnt++;
	}
	
	return cnt;
}

2.查找

(1)按序号查找FindKth

#define ERROR -1 /*一般定义为表中元素不可能取到的值*/

ElementType FindKth(List L, int K)
{
	Position P;
	int cnt=1;
	p=L;
	while(p&&cnt<K)
	{
		p=p->Next;
		cnt++;
	}
	if((cnt==K)&&p) return p->Data;
	else return ERROR;
}

(2)按值查找,即定位Find

#define ERROR NULL /*用空地址表示错误*/ 

Position Find(List L, ElementType X)
{
	Position P;
	p=L;
	while(p&&p->Data!=X)
	{
		p=p->Next;
	}
	if(p) return p;
	else return ERRPR;
}

3.插入

(1)不带头结点

#define ERROR NULL /*用空地址表示错误*/ 

List Insert(List L,ElementType X,int i)
{
	Position tmp,pre;
	
	tmp=(Position)malloc(sizeof(struct LNode));
	tmp->Data=X;  /*赋值可以在循环之前?*/
	/*如果新结点插入在表头*/ 
	if(i==1)
	{
		//tmp->Data=NULL;
		tmp->Next=L;
		return tmp;
	}
	else
	{
		int cnt=1;  /*查找位序为i=1的结点*/
		pre=L;
		while(pre&&cnt<i-1)
		{
			pre=pre->Next;
			cnt++;
		}
		if(pre==NULL||cnt!=i-1)  /*所找结点不在L中*/ /*为什么是或?*/ 
		{
			printf("插入位置参数错误\n");
			free(tmp);
			return ERROR;
		}
		else
		{
			/*找到了待插结点的前一个结点pre*/
			/*插入新结点,并返回表头L*/
			tmp->Next=pre->Next;
			pre->Next=tmp;
			return L; 
		}
	}
}

(2)带头结点

 

bool Insert(List L,ElementType X,int i)
{
	/*这里默认L有头结点*/
	Position tmp,pre;
	int cnt=0;
	
	pre=L;
	while(pre&&cnt<i-1)
	{
		pre=pre->Next;
		cnt++;
	}
	if(pre==NULL||cnt!=i-1)
	{
		printf("插入位置参数错误\n");
		return false;
	}
	else
	{
		tmp=(Position)malloc(sizeof(struct LNode));
		tmp->Data=X;
		tmp->Next=pre->Next;
		pre->Next=tmp;
		return true;
	}
}

4.删除

bool Delete(List L,int i)
{
	/*这里默认L有头结点*/
	Position tmp,pre;
	int cnt=0;
	
	pre=L;
	
	while(pre&&cnt<i-1)
	{
		pre=pre->Next;
		cnt++;
	}
	
	if(pre==NULL||cnt!=i-1||pre->Next==NULL)
	{
		/*所找结点或位序为i的结点不在L中*/
		/*pre==NULL||cnt!=i-1表示位序为i-1的结点不在L中*/ 
		/*pre->Next==NULL表示位序为i的结点不在L中*/
		printf("插入位置参数错误\n");
		return false;
	}
	else
	{
		tmp=pre->Next;
		pre->Next=tmp->Next;
		free(tmp);
		return true;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值