以递归方式从C ++中删除线性链接列表中的节点

时间:2017-03-01 04:38:25

标签: recursion

我正在尝试编写一个函数来递归地删除线性链表中任何位置的节点,但到目前为止它还没有工作。在开头删除但不在中间。这是我的代码

int remove(node* &head, char* data_to_delete)
{ 
  if(!head) return 0; // check if head is null

  if(!strcmp(head->data,data_to_delete)) //check if the first node is data
  { node* temp  = head->next;  //save head->next
    delete [] head->data;  //deallocate data 
    delete head; //delete the node
    head = temp;  //connect the node 
    return 1;
  }

  if(head->next && !strcmp(head->next->data,data_to_delete))//check if head->next is not null and head->next->data is equal to data
  {
      node* temp = head->next->next; 
      delete [] head->next->data;
      delete head->next;
      head->next = temp;
      return 1;
  }
  remove(head->next, data_to_delete);
}

如果我想沿着前一个指针拖动而不是向前看,我将如何修改它?感谢!!!!

0 个答案:

没有答案