【问题标题】:Remove node from linked list received as parameter C++从作为参数 C++ 接收的链表中删除节点
【发布时间】:2019-02-06 15:04:18
【问题描述】:

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

方法结构应该是这样的:

void LinkedList: : removeAt(ListElem *arg);

我该如何编写这个方法?因为我想不通

【问题讨论】:

  • 请提供minimal reproducible example。什么是ListElemLinkedList(它们是如何定义的)?
  • 因为我想不通请添加您的失败尝试+最小示例。

标签: c++ oop


【解决方案1】:
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;
  }
}

根据 cmets 更新。谢谢!

【讨论】:

  • 不要使用全局变量。
猜你喜欢
  • 2017-10-21
  • 2013-08-30
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 2016-01-02
  • 2016-03-02
  • 1970-01-01
相关资源
最近更新 更多