数据结构双链表求解
/*删除双链表第pos个位置的结点,并且返回该结点*/
int DeleteList(DLinkList *&L,int pos,ElemType &e)
{
DLinkList *p=L,*q;
int j=1;
while(j<pos&&p!=NULL)
{
++j;
p=p->next;
}
if(p->next==NULL)
return 0;
else
{
q=p->next;
if(q->next==NULL)
{
p->next=NULL;
e=q->data;
free(q);
}
else
{
p->next=q->next;
q->next->prior=p;
e=q->data;
free(p);
}
}
return e;
}
这个算法哪里出错了,编译有中断,求高手帮忙
[解决办法]
我感觉你这段程序逻辑很混乱,我说说我自己的看法,具体怎么改你自己看着办:
- C/C++ code
/*删除双链表第pos个位置的结点,并且返回该结点*/int DeleteList(DLinkList *&L,int pos,ElemType &e){DLinkList *p=L,*q;int j=1;while(j<pos&&p!=NULL) //你写这句无非是想防止pos超出表长范围{++j;p=p->next;}if(p->next==NULL) //运行到这里,不是j等于pos,就是p等于NULL,那么p->next怎么可能等于NULL呢?return 0;else{q=p->next;if(q->next==NULL){p->next=NULL;e=q->data;free(q); //按你的意思应该p指向的是pos个元素,怎么又变成删除q了呢?}else{p->next=q->next;q->next->prior=p;e=q->data; //这三句的意思应该是把q删除掉,然后把p和q->next连起来吧?free(p); //既然你删除的是q,怎么这里又要把删除呢?}}return e;}