为什么此代码不适用于删除C++中的节点


struct node{
int elem ;
node* next;
};
typedef node* list;
void RemoveAllX(int x, list&l){
list copy = l;
list q;
while (l != NULL){
if (l -> elem == x){
q = l;
l = l -> next;
delete q;
}
else
l = l -> next;
}
l = copy;
}

我要做的是从列表中删除每个以整数x为元素的节点。我希望如果我有一个列表,比如说[4]->[1]->[1]->[3],并调用RemoveAll(1,mylist(,我会得到列表[4]->[3],但是我用这个代码得到的是[4]->[trash]->[trush]->[3]。我假设if语句中的l = l -> next;行没有像我所理解的那样工作,任何帮助都感谢

  1. 这是删除单个节点的"某种"代码。您的方法显示RemoveAll
  2. 第二,将int与指针引用进行比较
  3. 您需要确保将链接列表的其余部分连接回已删除节点的上一个节点。如果你不这样做,你可能会失去剩下的清单
void deleteNode(Node *head, Node *n)  
{  
// When node to be deleted is head node  
if(head == n)  
{  
if(head->next == NULL)  
{  
cout << "There is only one node." << 
" The list can't be made empty ";  
return;  
}  
/* Copy the data of next node to head */
head->data = head->next->data;  
// store address of next node  
n = head->next;  
// Remove the link of next node  
head->next = head->next->next;  //this is the line you want... it connect the rest
// free memory  
delete n;  //can use free() as well , delete will call 
//deconstructor free wont...
return;  
}  

这是来自极客

因此,多亏了评论中留下的帮助,我能够想出这个工作但可能看起来很糟糕的代码。

struct node{
int elem ;
node* next;
};
typedef node* list;
void RemoveAllX(int x, list &l){
if (l != NULL){
list p = l; // Just a copy I'll be using, so I don't mess the original list up
list aux; // auxiliary variable I'll use to make the deletion.
while (p -> next != NULL){ // Here I look  for the any x's in every node BUT the first
if ((p -> next) -> elem == x){
aux = p -> next;
p -> next = (p -> next) -> next; // "Skip" or "go around" the node I want to remove 
delete aux; 
}
else{
p = p -> next;
}
}
if (l -> elem == x){ // And finally I check the first node the one I "missed" before
aux = l;
l = l -> next;
delete(aux);
}
}
}

相关内容

  • 没有找到相关文章

最新更新