day3 移出链表中值为x的节点

ListNode* removeElements(ListNode* head, int val) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点

        dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作

        ListNode* cur = dummyHead;

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

        head = dummyHead->next;
        delete dummyHead;
        return head;
    }

 

 

你可能感兴趣的:(算法)