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

移除链表元素

力扣题目链接

我的解法:

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

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;
    }
};
相关推荐
大千AI助手1 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
好好研究2 小时前
学习栈和队列的插入和删除操作
数据结构·学习
YuTaoShao3 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
生态遥感监测笔记3 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘
Tony沈哲4 小时前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东4 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845145 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
挺菜的5 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.8245 小时前
7.6 优先队列| dijkstra | hash | rust
算法