移除链表元素-力扣

一道基础的链表相关题目,在删除时对头节点进行单独处理。

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head != NULL && head->val == val){
            ListNode * t = head;
            head = head->next;
            delete t;
        }
        ListNode * cur = head;
        while(cur != NULL && cur->next != NULL){
            if(cur->next->val == val){
                ListNode * t = cur->next;
                cur->next = cur->next->next;
                delete t;
            }else{
                cur = cur->next;
            }
        }

        return head;
    }
};

另外一种写法是设置一个虚拟节点指向头节点,这样就无需对头节点进行单独处理,最后将head指向虚拟节点的下一个节点。

cpp 复制代码
class Solution {
public:
    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;
    }
};
相关推荐
小美爱刷题1 小时前
力扣DAY40-45 | 热100 | 二叉树:直径、层次遍历、有序数组->二叉搜索树、验证二叉搜索树、二叉搜索树中第K小的元素、右视图
数据结构·算法·leetcode
熬夜造bug1 小时前
LeetCode Hot100 刷题笔记(2)—— 子串、普通数组、矩阵
笔记·leetcode·矩阵
学习编程的gas2 小时前
数据结构——堆的实现和堆排序
数据结构·算法
Determined_man2 小时前
Mybatis-plus queryWrapper的使用
数据结构·数据库
lvchaoq3 小时前
图解力扣回溯及剪枝问题的模板应用
leetcode·深度优先·剪枝·回溯·递归
Swift社区3 小时前
LeetCode 252 会议室题全解析:Swift 实现 + 场景还原
算法·leetcode·swift
要下雨了吗3 小时前
指针数组 vs 数组指针
c语言·数据结构·c++·算法·visual studio
emmmmXxxy3 小时前
leetcode刷题-单调栈
算法·leetcode·职场和发展
MiyamiKK574 小时前
leetcode_数组 189. 轮转数组
python·算法·leetcode·职场和发展
武装头脑ing4 小时前
递增子序列
数据结构·算法