双链表的尾部添加节点问题
程序代码:#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list* prior;//前驱节点
struct list* pnext;//后继节点
}node,*ptrl;
int listcount;//全局变量,链表节点
//建立链表
ptrl createlist()
{
node* lhead,*lnew,*lend;
int createnum;
listcount=0; //存放数据
lhead=(node*)malloc(sizeof(node));
lend=lhead;
lend->pnext=NULL;
printf("输入数据:\n");
while((scanf("%d",&createnum))!=0)
{
if(createnum==0)
{
break;
}
listcount++;
lnew=(node*)malloc(sizeof(node));
lnew->data=createnum; //数据存入链表
if(lhead==NULL)
{
lhead=lnew;
lend=lhead;
}
else
{
lnew->pnext=lend;
lnew->prior=lend;
lend->pnext=lnew;
lend=lnew;
}
lend->pnext=NULL;
}
return lhead;
}
//在指定节点添加节点数据
ptrl addnum(int num,node* lhead,int listdata)
{
node *lnew,*temp; //temp用来遍历到指定节点的LIST指针,lnew用于保存新节点数据
int addcount=0;
lnew=(node*)malloc(sizeof(node));
temp=lhead;
lnew->data=listdata;
//在表头插入数据
if(temp->pnext==NULL)
{
lnew->pnext=lhead;
temp->pnext=lnew->pnext;
temp->prior=lnew;
listcount++;
}
//如果在表中插入节点数据
if(temp->pnext!=NULL&&listcount!=num-1)
{
while(addcount<num)
{
temp=temp->pnext;
addcount++;
}
lnew->pnext=temp;
lnew->prior=temp->prior;
temp->prior->pnext=lnew;
temp->prior=lnew;
listcount++;
}
else
{ //在表尾插入节点数据
for(addcount=0;addcount<num-1;++addcount)
{
temp=temp->pnext;
}
listcount++;//链表节点递增一次
lnew->pnext=temp; //接入链表
lnew->prior=temp->prior;
temp->prior->pnext=lnew;
temp->pnext=NULL;
}
return lhead;
}
void prit(node* lhead)
{
node* ltemp;
ltemp=lhead->pnext;
if(lhead==NULL)
{
printf("空链表");
exit(-1);
}
while(ltemp!=NULL)
{
printf("%d\n",ltemp->data);
ltemp=ltemp->pnext;
}
}
int main()
{
node* temp;
int listnum;//节点
int listdata;//数据
temp=(node*)malloc(sizeof(node));
temp=createlist();
prit(temp);
printf("输入要添加的节点:");
scanf("%d",&listnum);
printf("输入要添加的数据:");
scanf("%d",&listdata);
temp=addnum(listnum,temp,listdata);
prit(temp);
return 0;
}
调试结果:
程序代码://如果在表中插入节点数据
if(temp->pnext!=NULL&&listcount!=num-1)
{
while(addcount<num)
{
temp=temp->pnext;
addcount++;
}
lnew->pnext=temp;
lnew->prior=temp;
temp->prior->pnext=lnew;
temp->prior=lnew;
listcount++;
}
else
{ //在表尾插入节点数据
for(addcount=0;addcount<num-1;++addcount)
{
temp=temp->pnext;
}
listcount++;//链表节点递增一次
lnew->pnext=temp; //接入链表
lnew->prior=temp;
temp->prior->pnext=lnew;
temp->pnext=NULL;
}想问一下这是哪里出了问题?在表尾添加节点数据,实际运行时却在表尾的前一个节点添加了。。








谢谢各位版主,看完回复我哭了。重新整理思路,重新画流程 重新写过。。。。
