//*******************双向非循环链表**********************//
#include"myhead.h"
```typedef struct dou_list_node
{
int data;
struct dou_list_node *next;
struct dou_list_node *prev;
}dou_list,*dou_link;
```dou_link init_list()
{
dou_link head_ptr=malloc(sizeof(dou_list));
head_ptr->prev=NULL;
head_ptr->next=NULL;
return head_ptr;
}
```dou_link creat_node(int data)
{
dou_link newnode_ptr=malloc(sizeof(dou_list));
newnode_ptr->data=data;//数据域
newnode_ptr->next=NULL;//指针域
newnode_ptr->prev=NULL;//指针域
return newnode_ptr;
}
```int insert_tailnode(int data,dou_link head_ptr)//尾增
{
dou_link newnode_ptr=creat_node(data);
if(newnode_ptr==NULL)
{
puts("新节点传创建失败");
return -1;
}
dou_link p=head_ptr;//寻找尾节点
while(p->next)
{
p=p->next;
}
//后增数据
newnode_ptr->prev=p;
p->next=newnode_ptr;
return 0;}
int PriDouList(dou_link head_ptr)
{
dou_link p=head_ptr->next;
if(p==NULL)
{
puts("链表为空");
return -1;
}
puts("链表数据如下(顺序):");
while(1)
{
printf("%d\n",p->data);
if(p->next==NULL)
break;
p=p->next;
}
puts("链表数据如下(逆序):");
while(p)
{
printf("%d\n",p->data);
p=p->prev;
if(p==head_ptr)
break;
}
return 0;
}
```int NumOfListNode(dou_link head_ptr)//计算链表的节点数量(不包括头节点)
{
dou_link p=head_ptr->next;
if(p==NULL)
{ puts("链表为空");
return -1;
}
int count=1;
while(p=p->next)
{
count++;
}
return count;
}
```int NumOfSpecifiedData(int des_data,dou_link head_ptr)//计算链表中指定数据的数量(不包括头节点)
{
int count=0;
dou_link p=head_ptr;
if(p->next==NULL)
{
puts("链表为空");
return -1;
}
while(p=p->next)
{
if(p->data==des_data)
{
count++;
}
}
return count;
}
int insert2_midnode(int des_data,int newdata,dou_link head_ptr)
{
while(head_ptr->next==NULL)
{
puts("无法对指定位置插入数据,链表为空");
return -1;
}
int num_spe_data=NumOfSpecifiedData(des_data,head_ptr);//寻找目标数据在链表中的数量
if(num_spe_data==0)
{
puts("找不到指定数据");
return -1;
}
else
{
//创建对应数量的新节点
dou_link newnode_ptr[num_spe_data];
for(int i=0;i<num_spe_data;i++)
{
newnode_ptr[i]=creat_node(newdata);
//printf("%p\n%d\n",newnode_ptr[i],newnode_ptr[i]->data);
}
//找到目标位置并插入数据
dou_link p=head_ptr->next;
while(1)
{
int i=0;
if(p->data==des_data&&p->next!=NULL)
{
newnode_ptr[i]->next=p->next;
newnode_ptr[i]->prev=p;
p->next=newnode_ptr[i];
newnode_ptr[i]->next->prev=newnode_ptr[i];
i++;
p=p->next;
}
else if(p->data==des_data&&p->next==NULL)
{
newnode_ptr[i]->prev=p;
p->next=newnode_ptr[i];
return 0;
}
p=p->next;
if(p==NULL)
return 0;
}
}
}
```int main()
{
dou_link head_ptr=init_list();//初始化
for(int i=1;i<4;i++)
{
insert_tailnode(i,head_ptr);
}
insert_tailnode(2,head_ptr);
PriDouList(head_ptr);
int des_data,newdata;
puts("输入目标节点数据和新节点数据");
scanf("%d%d",&des_data,&newdata);
insert2_midnode(des_data,newdata,head_ptr);
PriDouList(head_ptr);
}
上面的代码希望指定一个数据,在链表中找到相同的数据节点,并往后插入一个数据,如果指定数据在链表中有多个,则插入相应数量的新节点。
情况:编译无报错,如果指定的数据在链表中只有一个,打印出的链表无误。如果有多个,打印出来的链表就死循环了。
弄了好久了,希望热心人帮忙解答,谢谢。