Leetcode—203. 移除链表元素【简单】

2024每日刷题(一零九)

Leetcode—203. 移除链表元素

Leetcode—203. 移除链表元素【简单】_第1张图片

实现代码

/**
 * 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) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* cur = head;
        ListNode* pre = dummy;
        if(head == nullptr) {
            return head;
        }
        while(cur) {
            if(cur->val == val) {
                pre->next = cur->next;
                delete cur;
                cur = pre->next;
            } else {
                pre = cur;
                cur = cur->next;
            }
        }
        pre->next = nullptr;
        return dummy->next;
    }
};

运行结果

Leetcode—203. 移除链表元素【简单】_第2张图片

尾插法实现代码

/**
 * 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) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* p = head;
        ListNode* r = dummy;
        if(head == nullptr) {
            return head;
        }
        while(p) {
            if(p->val != val) {
                r->next = p;
                r = p;
                p = p->next;
            } else {
                ListNode *q = p;
                r->next = q->next;
                delete q;
                p = r->next;
            }
        }
        r->next = nullptr;
        return dummy->next;
    }
};

运行结果

Leetcode—203. 移除链表元素【简单】_第3张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,链表,算法,c++,数据结构,经验分享)