双向链表删除错误

写一个双向链表实现插入删除遍历

ps:一般插入遍历没什么问题,主要是删除老是出现不可预期的结果,其实是对指针的操作错误。尤其要主要头指针和尾指针

如果执行删除一个元素操作后发现待删除元素及此元素之前的所有数据都被删除,应该检查下是否待删元素的pre指向为头指针head而非它的前一个元素。

一般这种情况是插入函数Insert()在实现的时候插入的元素前后指向不正确。只要链表所有next指针是正确在遍历的时候不会发现错误,但是删除是要指定元素的pre指向的要注意!


如下:

typedef struct node
{
int data;
node* pre;
node* next;
};
class List{
public:
List();
~List();
node* create();
node* insert(int );
node *remove(int);
node* find();
void travle();
node* getlist()
{
return head;
}
private:
int m_justbak;
node* head;
};

===================链表实现

List::List(){head=NULL;}
List::~List(){}
node* List::create(){
if(head==NULL)
{
head=new node;
head->data=0;
head->pre=NULL;
head->next=NULL;
return head;
}
return NULL;
}
node* List::insert(int str){
node* ptr=new node;
if(head->next==NULL)
{
ptr->data=str;
ptr->next=NULL;
ptr->pre=head;
head->next=ptr;
}
else
{
ptr->data=str;
ptr->next=head->next;
ptr->pre=head;
head->next->pre=ptr;//指定头指针的下一个节点的pre指向为新加入的元素。如果没有这句遍历不会出错但是删除会出错
head->next=ptr;
}
return head;
}


node *List::remove(int dec){
node* pcur=head->next;
if(pcur==NULL){cout<<"empty list please insert data"<<endl; return NULL;}
node* p=pcur->next;

while(pcur->next!=NULL )
{
if(pcur->data==dec)
{
//pcur->pre->next=pcur->next;
//pcur->next->pre=pcur->pre;
pcur->pre->next=p;
p->pre=pcur->pre;
delete pcur;
pcur=NULL;
pcur=p;
p=p->next;
continue;
}
pcur=pcur->next;
p=pcur->next;
}
return head;
}
node* List::find(){
return NULL;
}
void List::travle(){
node* p=head->next;

while(p!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值