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

移除链表元素

力扣题目链接

我的解法:

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

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;
    }
};
相关推荐
mit6.8244 小时前
bfs|栈
算法
CoderYanger6 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz6 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗6 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java6 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*6 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z7 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3457 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48077 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香8 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展