数据结构学习之 链表

链表的定义
#define NULL 0
#define LEN sizeof(Lnode)

typedef int elemtype;
struct Lnode
{
	elemtype data;
	struct Lnode *next;
};
struct Lnode *head,p;

1单链表的初始化
struct Lnode *initlist(struct Lnode *head)
{
	head=NULL;
}
2.单链表的置空
struct Lnode *clearlist(struct Lnode *head)
{
	struct Lnode *p;
	while(head!=NULL)
	{
		p=head;
		head=head->next;
		free(p);
	}
}
3.判断单链表是否为空
int emptylist(struct Lnode *head)
{
	return(head!=NULL);
}
4.求单链表的长度
int lengthlist(struct Lnode *head)
{
	struct Lnode *p;
	int j=0;
	p=head;
	while(p!=NULL)
	{
		p=p->next;
		j++;
	}
	return (j);
}
5.取单链表的一个元素
elemtype getlist(struct Lnode *head ,int i)
{
	int j=0;
	struct Lnode *p;
	p=head;
	while ((p!=NULL)&&(j<i))
	{
		p=p->next
		j++;
	}
	if(p!=NULL)
		return(p->data);
	else 
		return(0);
}
6.在单链表中查找数据元素
 elemtype search(struct Lnode *head ,elemtype key)
 {
	 struct Lnode *p;
	 int z=0;
	 if(head==NULL)
		 printf("its empty")
	else
		p=head;
	while(p->data!=key&&p->next!=NULL)
		p=p->next;
	if(p->data==key)
		z=key;
	else
		z=0;
	return(z);
 }
 
7.在单链表中删除元素
struct Lnode *delete(struct Lnode *h ,int i)
{
	struct Lnode *p,*q;
	p=h;
	int j=1;
	while((j<i)&&(p!=NULL))
	{
		q=p;
		p=p->next;
		j++;
	}
	if((p!=NULL)&&(p->next!=NULL))
	{
		q->next=p->next;
		free(p);
	}
}
8.在单链表中给定位置pos_key前插入关键字ins_key
insert(struct Lnode *h,int pos_key,int ins_key)
{
	struct Lnode *p,*q,*s;
	if(h==NULL)
	{
			s=(struct Lnode *) malloc(LEN);

		s->data=ins_key;
		s->next=h;
		h=s;
	}//把关键字插入头元素
	else if (h->data==pos_key)
	{		s=(struct Lnode *) malloc(LEN);

		s->data=ins_key;
		s->next=h;
		h=s;
	}
	else if (h->next==NULL&&h->data!=pos_key)
	{		s=(struct Lnode *) malloc(LEN);

		s->data=ins_key;
		s->next=NULL;
		h->next=s;
	}
	else if (h->next!=NULL&&h->data!=pos_key)
	{
		s=h;
		p=s->next;
		while(p->next!=NULL&&p->data!=pos_key)
		{
			s=p;
			p=p->next;
		}
				s=(struct Lnode *) malloc(LEN);
				s->data=ins_key;
				s->next=p->next;
				p->next=s;
		
	}
}
 

双链表

typedef int elemtype;
struct Dnode{
	elemtype data;
	struct Dnode *fnext;
	struct Dnode *bnext;
};
struct Dnode *Dlist;
1.在双链表中p指向的节点前插入一个数据元素x
insdlist (struct Dnode *p,elemtype x)
{
	struct Dnode *q ,*k;
	q=(struct Dnode *) malloc (sizeof(struct Dnode));
	q->date=x;
	q->bnext=p;
	q->fnext=p->fnext;
	k=p->fnext;
	k->bnext=q;
}
2.双链表的的删除
deldlist(struct Dnode *p)
{
	p->fnext->bnext=p->bnext;
	p->bnext->fnext=p->fnext;
	free(p);
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值