链表

 

链表相关典型例题

倒序获得链表值

链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/lh2xpc/

题目解析: 

用递归方法

利用递归,先递推至链表末端;回溯时,依次将节点值加入列表,即可实现链表值的倒序输出。

终止条件: 当 head == None 时,代表越过了链表尾节点,则返回空列表;

递推工作: 访问下一节点 head.next ;
回溯阶段:
  将当前节点值 head.val 加入列表 tmp ;

复制代码
class Solution {
public:
    vector<int> reverseBookList(ListNode* head) {
        recur(head);
        return res;
    }
private:
    vector<int> res;
    void recur(ListNode* head) {
        if(head == nullptr) return;
        recur(head->next);
        res.push_back(head->val);
    }
};
复制代码

删除链表节点

 链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/lh2jri/

解题思路:
本题删除值为 val 的节点分需为两步:定位节点、修改引用。

定位节点: 遍历链表,直到 head.val == val 时跳出,即可定位目标节点。
修改引用: 设节点 cur 的前驱节点为 pre ,后继节点为 cur.next ;则执行 pre.next = cur.next ,即可实现删除 cur 节点。

复制代码
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head->val == val) return head->next;
        ListNode *pre = head, *cur = head->next;
        while(cur != nullptr && cur->val != val) {
            pre = cur;
            cur = cur->next;
        }
        if(cur != nullptr) pre->next = cur->next;
        return head;
    }
};
复制代码

 

 链表反转

链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/lhnyoe/

解题思路:

用双指针,流程见注释

复制代码
class Solution {
public:
    ListNode* trainningPlan(ListNode* head) {
        ListNode *cur = head, *pre = nullptr;
        while(cur != nullptr) {
            ListNode* tmp = cur->next; // 暂存后继节点 cur.next
            cur->next = pre;           // 修改 next 引用指向
            pre = cur;                 // pre 暂存 cur
            cur = tmp;                 // cur 访问下一节点
        }
        return pre;
    }
};
复制代码

 

posted @   xsgcumt  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-11-01 FreeRTOS(1):任务管理
2023-11-01 江科大STM32(1):第一个外设GPIO
点击右上角即可分享
微信分享提示