#GESP2835. [GESP]L5-202412-Q2835-S

[GESP]L5-202412-Q2835-S

为了方便链表的增删操作,一些算法生成一个虚拟头节点,方便统一删除头节点和其他节点。下面代码实现了删除链表中值为 val 的节点,横线上应填的最佳代码是( )。

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int val):val(val), next(nullptr){}
};

void removeElements(ListNode* head, int val) {
    if (head == nullptr) {
        return;
    }
    ListNode* cur;
    ListNode* dummyHead = new ListNode(0); //虚拟头节点
    // 在此处填入代码

    while(cur ->next != nullptr) {
        if(cur->next->val == val) {
            ListNode* tmp = cur->next;
            cur->next = cur->next->next;
            delete tmp;
            tmp = nullptr;
        }
        else {
            cur = cur ->next;
        }
    }
    head = dummyHead->next;
    delete dummyHead;
    dummyHead = nullptr;
}

{{ select(1) }}

  • dummyHead->next = head; cur = dummyHead;
  • dummyHead->next = head->next; cur = dummyHead;
  • dummyHead->next = head; cur = dummyHead->next;
  • dummyHead->next = head->next; cur = dummyHead->next;