每日一题算法——移除链表元素、反转链表

移除链表元素

力扣题目链接

我的解法:

注意细节:要删掉移除的元素。

c++ 复制代码
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head!=nullptr){
            if(head->val==val){
                head=head->next;
            }
        }
        ListNode* nowhead = head;
        while(nowhead){
            
            if(nowhead->next->val == val){
                if(nowhead->next->next == nullptr){
                    nowhead->next =nullptr;
                }else{
                    nowhead->next=nowhead->next->next;
                }
                
            }
            nowhead = nowhead->next;
        }
        return head;
    }
};

//修改后
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head != NULL && head->val==val){
            ListNode* tmp = head;
            head = head->next;
            delete tmp;
        }
        ListNode* nowhead = head;
        while(nowhead !=NULL && nowhead->next !=NULL ){
            
            if(nowhead->next->val == val){
                    ListNode* tmp=nowhead->next;
                    nowhead->next=nowhead->next->next;
                    delete tmp;
                }else{
                     nowhead = nowhead->next;
                }
                
        }
        return head;
        
    }
};

方法二:

增加一个伪头结点dummyhead,dummyhead->next = head;

这样可以统一头结点和后续节点的删除方式。

c++ 复制代码
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {

        ListNode* dummyhead = new ListNode(0);\\记得定义
        dummyhead->next =head;
        ListNode* nowhead =dummyhead;
        while(nowhead !=NULL && nowhead->next !=NULL ){
            
            if(nowhead->next->val == val){
                    ListNode* tmp=nowhead->next;
                    nowhead->next=nowhead->next->next;
                    delete tmp;
                }else{
                     nowhead = nowhead->next;
                }
                
        }
        return dummyhead->next;
        
    }
};

反转链表

力扣题目链接

c++ 复制代码
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* cur = head;
        while(cur!=nullptr){
            ListNode * tmp = cur->next;
            cur->next =prev;
            prev =cur;
            cur =tmp;
        }
        return prev;
    }
};
相关推荐
dazzle1 小时前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵1 小时前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
张张努力变强1 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发1 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
wWYy.1 小时前
数组快排 链表归并
数据结构·链表
张登杰踩1 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao1 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0072 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零2 小时前
变点检测算法PELT
算法
深鱼~2 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann