2024.1.25

双链表的任意位置插入元素

//双链表任意位置插入
Doublelink insert_element(Doublelink head,int index,datatype key)\
{
	//创建一个结点
	Doublelink s=creat_Node();
	s->data=key;
	//首先找到所插入的位置
	int count=1;
	Doublelink p=head;
	if(index==1||head==NULL)//在为空和第一个位置插入
    return head=insert_head(head,key);
	//如果只有一个元素的情况下
	if(head->next==NULL)
    return	head=insert_rear(head,key);
	while(p)//在第二个以及往后的位置插入
	{
		count++;
		p=p->next;
	if(count==index)
	{
		s->next=p;
		p->prior->next=s;
		s->prior=p->prior;
		p->prior=s;
	}
	}
//	printf("%d\n",count);
	return head;
}

2024.1.25_第1张图片

双链表按任意位置删除

//双链表按任意位置删除
Doublelink del_key(Doublelink head,int index)
{
	if(NULL==head)
	{
		return head;
	}
    else if(head->next==NULL)
	{
			free(head);
			head=NULL;
			return head;
	}
	else{
		Doublelink p=head;
	int 	count=1;
 	while(p)
		{
			count++;
  			p=p->next;//p位于要删除的元素
			if(p->next==NULL)//删除最后一个元素
			{
		return head=del_rear(head);
			}
			if(count==index)//找到要删除的元素的位置(2-n-1)
		{
			p->prior->next=p->next;
			p->next->prior=p->prior;
			free(p);
			p=NULL;
		}
		}
	return head;
}
}

2024.1.25_第2张图片

你可能感兴趣的:(数据结构,算法)