双链表插入节点问题,麻烦各位给看下这个程序哪里有问题,谢谢
#include<iostream>using namespace std;
struct node{
int data;
node *pre,*next;
};
node *head,*p,*r,*a;
void insert(int x,int y)
{
int z=1;
a=new node;
a->data=x;
p=head->next;
while(p->next!=NULL&&z<y )
{
p=p->next;
z++;
}
if(p==NULL) cout<<"no this position"<<endl;
else
{
a->pre=p->pre;
p->pre=a;
a->next=p;
p->pre->next=a;
}
}
int main()
{
int x,a,b;
cin>>x;
head=new node;
r=head;
while(x!=-1)
{
p=new node;
p->data=x;
p->next=NULL;
p->pre=NULL;
r->next=p;
if(r!=head) p->pre=r;
r=p;
cin>>x;
}
cin>>a>>b;
insert(a,b);
p=head->next;
while(p->next!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<p->data<<endl;
system("pause");
return 0;
}
输入1 2 3 4 5 6 -1 5 3
输出1 2 3 4 5 6
把输出部分改成如下:
p=r;
while(p->pre!=NULL)
{
cout<<p->data<<" ";
p=p->pre;
}
cout<<p->data<<endl;
输出为6 5 4 3 5 2 1
不明白是为什么,麻烦各位了,谢谢