优选算法_翻转链表_头插法_C++

一.题目解析

算法解析:

结合画图和头插代码就很好理解了

二.代码编写:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * 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* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr)return head;

        ListNode*newhead=new ListNode(0);
        ListNode*cur=head;
        while(cur!=nullptr)
        {
            ListNode*next=cur->next;//注意顺序和位置
            cur->next=newhead->next;
            newhead->next=cur;
            cur=next;
        }
        cur=newhead->next;
        delete newhead;
        return cur;
    }
};
相关推荐
yiangL_5 分钟前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
JosieBook38 分钟前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
电科_银尘43 分钟前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao1 小时前
算法68,字符串相乘
算法
Huangjin007_2 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
geovindu2 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk81633 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾3 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
驭渊的小故事4 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
炸膛坦客4 小时前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机