leetcode-代码随想录-链表-移除链表元素

题目

链接:203. 移除链表元素 - 力扣(LeetCode)

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

复制代码
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
c++ 复制代码
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        
    }
};
思路 & 代码
  1. 由于要删除的节点可能是头节点,所以为了方便采用 虚拟头节点 的方法来移除元素。
  2. 设置虚拟头节点:ListNode* dummyHead = new ListNode(0);
  3. 移除元素:找到目标val节点 的前一个节点 cur,将其指向下下一个节点cur->next = cur->next->next
  4. 释放被移除元素的内存

注意点: 在判断cur->nextcur->val时,要先判断cur不为空,否则就是报空指针错误

c++ 复制代码
#include <iostream>
using namespace std;

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

void printLinkedList(ListNode* head){
    ListNode* cur = head;
    while(cur != nullptr) {
        cout << cur->val << " ";
        cur = cur->next;
    }
    cout << endl;
}

int main() {
    
    int n, m;
    ListNode* dummyHead = new ListNode(0);
    while(cin >> n){
        if(n == 0){
            cout << "list is empty" << endl;
            continue;
        }

        ListNode* cur = dummyHead;

        while(n--){
            cin >> m;
            ListNode* newNode = new ListNode(m);
            cur->next = newNode;
            cur = cur->next;
        }
    }

    ListNode* head = dummyHead->next;
    delete dummyHead;
    printLinkedList(head);

    int val = 6;
    Solution obj;
    ListNode* result = obj.removeElements(head,val);
	
    printLinkedList(result);
}

时间复杂度: O(n)

空间复杂度: O(1)

相关推荐
小L~~~1 小时前
基于贪心策略的混合遗传算法求解01背包问题
python·算法
洛水水2 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
jieyucx2 小时前
Go 语言 sort 包详解:从基础排序到自定义排序(含底层原理+零基础看懂)
算法·golang·排序算法·sort
叁散3 小时前
ESP32 LCD1602显示实验报告
算法
过期动态3 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒3 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
君为先-bey3 小时前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
洛水水3 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师3 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅3 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表