注册 登录
编程论坛 C++教室

双链表插入节点问题,麻烦各位给看下这个程序哪里有问题,谢谢

lucashl 发布于 2021-08-27 21:54, 2983 次点击
#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
不明白是为什么,麻烦各位了,谢谢
3 回复
#2
rjsp2021-08-31 08:53
p->pre->next=a;
改为
a->pre->next=a;

不过,你这么多全局变量下用,基本上也完了
#3
lucashl2021-09-02 21:22
回复 2楼 rjsp
调试成功,万分感谢!!!
#4
lucashl2021-09-02 21:23
回复 2楼 rjsp
"不过,你这么多全局变量下用,基本上也完了"请问这句话是什么意思,没看懂
1