从作为参数C ++接收的链表中删除节点

时间:2019-02-06 15:04:19

标签: c++ oop

我有一个LinkedList类,我想编写一个方法,该方法将作为方法中的参数接收的节点作为指针删除。

方法结构应如下所示:

void LinkedList: : removeAt(ListElem *arg);

我该如何编写此方法?因为我无法弄清楚

1 个答案:

答案 0 :(得分:0)

void LinkedList: : removeAt(LinkedList *ll, ListElem *arg) {
  if (!ll->head) return; // ll is your linked list object
  if (ll->head == arg) {
    struct ListElem *head = ll->head;
    ll->head = head->next;
    delete head;
    return;
  }
  struct ListElem *current = ll->head;
  while (current->next) {
    if (current->next == arg) {
      struct ListElem *next = current->next;
      current->next = next->next;
      delete next;
      break;
    }
    current = current->next;
  }
}

根据评论进行了更新。谢谢!