weixin_46084654 2021-06-10 17:16 采纳率: 0%
浏览 14

C++双相链表,插入元素,但是总不成功,请大神帮忙找出错误

#include<iostream>
using namespace std;
struct node{
int data;
node *pre,*next;
};
node *head,*p,*r;
int a,b;
void insert(node *head,int i,int x)
{
node *s,*p;
int j;
s=new node;
s->data=x;
p=head;
j=0;
while((p->next!=NULL)&&(j<i))
{
p=p->next;
j=j+1;
}
if(p==NULL)
cout<<"no this position!";
else
{
s->pre=p->pre;
p->pre=s;
s->next=p;
p->pre->next=s;
} 
}
int main()
{
cin>>a>>b;
int x;
head=new node;
r=head;
cin>>x;
while(x!=-1)
{
p=new node;
p->data=x;
p->next=NULL;
p->pre=r;
r->next=p;
r=p;
cin>>x;
}
insert(head,a,b);
p=head->next;
while(p->next!=NULL)
{
cout<<p->data<<" ";
p=p->next; 
}
cout<<p->data<<endl;
return 0;
}
  • 写回答

2条回答 默认 最新

  • qfl_sdu 2021-06-10 17:43
    关注

    1.插入位置是 0的时候需要单独考虑

    2.后面插入的逻辑不对,应该是

    nide*  t = p->pre;

    t->next = s; 

    s->pre = t;

    s->next = p;

    p->pre = s;

    评论

报告相同问题?

悬赏问题

  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题
  • ¥20 有谁能看看我coe文件到底哪儿有问题吗?
  • ¥20 我的这个coe文件到底哪儿出问题了
  • ¥15 matlab使用自定义函数时一直报错输入参数过多
  • ¥15 设计一个温度闭环控制系统
  • ¥100 rtmpose姿态评估
  • ¥15 通联支付网上收银统一下单接口