我试图在一个函数中删除链表中的所有特定键元素。 即如果链表有1 2 2 3 4 4 5 5 8 2 6 32 4 6 7 7那么如果我传递函数2那个函数删除链表中的所有2个
我的链接列表在这里
class float_list
{
struct node
{
double data;
struct node *next;
};
node *head;
public:
float_list(void)
{
head = nullptr;
};
void appendNode(double);
void print_list();
void deleteNode(double);
};
现在我的deleteNode(double在这里)
void float_list::deleteNode(double num)
{
node *nextptr, *previousptr = nullptr;
nextptr=head;
if(!head->data){return;}
if(head->data==num)
{
nextptr= head->next;
delete head;
head = nextptr;
}
else
while(nextptr)
{
previousptr= nextptr;
if(nextptr->data==num)
{
previousptr->next = nextptr->next;
delete nextptr;
cout<<"I Found the --> "<<num<<" is going to be deleted"<<endl;
nextptr = previousptr;
//nextptr = nextptr->next;
}
nextptr = nextptr->next;
}
delete nextptr;
delete previousptr;
}
我尝试了各种不同的方法,但总是遇到访问冲突错误。如果可能的话,请给我概念和代码提示。谢谢 代码在win32 Vs2010应用程序中
答案 0 :(得分:1)
我可以追查两个问题:
operator==
来检查两个浮动的相等性
点数,浮点运算有问题 -
它们不准确,结果可能不像你期望的那样[不能解决你的问题,但肯定是一个问题] 您的previousptr
和nextptr
是相同的[他们都指向同一个地址!]。您应该在当前迭代之前修改previousptr
。 [在nextptr = nextptr->next;
之前]。因此,当您删除nextptr
并稍后设置:
nextptr = previousptr;
nextptr = nextptr->next;
您实际上是在访问刚删除的元素,这会导致您的非法访问。
答案 1 :(得分:1)
while循环结束后会发生什么。那么,nextptr == NULL。删除NULL ==问题。
试试这个:
node *previous = nullptr, *current = head, *temp;
while(current){
temp = current->next;
if(abs(current->data - num) < MARGIN_OF_ERROR){
if (previous){
previous->next = current->next;
} else {
head = current->next;
}
delete current;
} else{
previous = current;
}
current = temp;
}
答案 2 :(得分:1)
public void removeData( double data )
{
if ( this.node == null ){ return; }
if ( this.node->data == data ){
this.node = this.node.node;
}
this.node.removeData( data );
}
答案 3 :(得分:0)
可能这可以通过递归完成,但这是一个移动指针解决方案:
void removenumber(node **head, int value)
{
node * current;
node * prev;
node * tmp;
current = (*head);
if ( current == NULL) return;
prev = current;
current = current->next;
while( current!= NULL && current->next != NULL)
{
if ( current->data == value)
{ //remove current
tmp = current->next;
prev->next = current->next;
free(current);
current = tmp;
//previous is the same
continue;
}
current = current->next;
prev = prev->next;
}
// now current->next != NULL check it
if(current!=NULL) //what is current was deleted?
{
if(current->data == value )
{
prev->next = NULL;
free(current);
}
}
if ( (*head)->data == value) //remove head
{
tmp = (*head)->next;
free(*head);
*head = tmp;
}
}