【链表-简单】剑指 Offer 24. 反转链表(修改指针、辅助数组,递归 三种解法)

万物的算法日记|第三天 笔者自述:一直有一个声音也一直能听到身边的大佬经常说,要把算法学习搞好,一定要重视平时的算法学习,虽然每天也在学算法,但是感觉自己一直在假装努力表面功夫骗了自己,没有规划好自己的算法学习和总结,因为后半年也该找实习了,所以每日的算法题要进行恶补,勤能补拙,因此有了这一个算法日记系列;也希望对您有帮助,和您一起通关算法!致谢算法语言:java题目来源:力扣–书本–初级算法,addLast(E e):将元素添加到链表末尾,相当于将元素压入栈顶。 阅读详情

【题目】
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
【示例】
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
【限制】
0 <= 节点个数 <= 5000
【代码】
【Python】
在这里插入图片描述

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        num=[]
        t=head
        while t:
            num.append(t.val)
            t=t.next
        num=num[::-1]
        t=head
        i=0
        while t:
            t.val=num[i]
            i+=1
            t=t.next
        return head

【方法2】
在这里插入图片描述

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None:
            return head
        pre,now=head,head.next
        while now:
            t=now.next
            now.next=pre
            if pre==head:
                pre.next=None
            pre=now
            now=t
        return pre


【递归】
在这里插入图片描述

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        newHead = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return newHead
Minitab田口设计实战:如何用正交试验优化遗传算法参数(附完整操作步骤) 本文详细介绍了如何利用Minitab田口设计进行遗传算法参数优化,通过正交试验方法显著提升效率。文章涵盖实验设计、Minitab操作步骤、结果分析及高级技巧,帮助工程师快速掌握这一工业级优化技术,实现算法性能的显著提升。 阅读详情

相关推荐

从零部署思澈科技SiFli-Solution:避坑指南与实战排错

本文详细介绍了从零部署思澈科技SiFli-Solution开发环境的完整流程与实战排错指南。重点解析了Keil uVision5版本选择、Butterfli工具路径配置等关键步骤,并针对Keil路径报错、函数冲突等高频问题提供了具体解决方案,帮助开发者高效避坑,快速搭建稳定的嵌入式开发环境。

devops8pract的博客 530

摒除一切封建迷信之递归并不难------排序2

剖析递归行为和递归行为时间复杂度的估算 一个递归行为的例子 master公式的使用 T(N) = a*T(N/b) + O(N^d) 1) log(b,a) &gt; d -&gt; 复杂度为O(N^log(b,a)) 2) log(b,a) = d -&gt; 复杂度为O(N^d * logN) 3) log(b,a) &lt; d -&gt; 复杂度为O(N^d) 补充阅读:...

qq_43193797的博客 225

Allegro 16.6 高级技巧实战:用Region规则和动态间距搞定高密度连接器布局布线

本文深入探讨了Allegro 16.6在高密度连接器布局布线中的高级技巧,重点介绍了Region规则和动态间距属性的应用。通过局部规则覆盖和分层控制,解决0.5mm以下引脚间距的布线难题,提升PCB设计效率和质量。

weixin_30352645的博客 441

链表-反转链表

题目:https://leetcode-cn.com/problems/reverse-linked-list/ 题意:反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

jsdoulaoula的博客 142

Windows版本Carla(含RoadRunner插件)源码安装+RoadRunner地图导入

通过跳转浏览器账号密码登录github,不要选择Fine-grained personal access tokens,在git clone时会显示非授权,也不要使用Windows凭据!核心指令:编译PythonAPI–make PythonAPI,,编译Server–make launch,封装”游戏“–make package。完成安装后,在已安装->2022版本右侧->更多->导入配置,选择配置文件(需将配置文件内容更新为手册内容,如下图)->详细信息,更新。不要修改版本,执行上面指令即可!

winnizap的博客 1469

「UG/NX」多功能dll集成一个dll的三种方法

C++多功能集成一个dll的三种方法。

何曾参静谧的博客 1390

反转链表问题详解

本文主要解决力扣上与反转链表相关的三道题目 26. 反转链表(简单) 92. 反转链表 II(中等) 25. K 个一组翻转链表(困难) 对应的目录如下图 1、单链表全反转 第206题,给定一个链表,要求得到一个反转后的链表。例子如下: 可以看到题目要求是要对链表进行全反转,也就是对于链表上的每个节点来说,将它的前驱和后继的位置进行互换,使得原来的前驱变成后继,原来的后继变成前驱。 这道题的难点是在借助其他辅助指针修改每个节点的前驱和后继的时候,如果不注意修改的先后顺序,很容易就发生节点相互覆盖,形成回

WDlanguang的博客 541

Cesium 相机操作

Cesium 提供了三种方式对相机的位置进行摆放。

虎康的博客 2594

面试题24 反转链表 列表/ 递归 Python3

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 解法1 不改变链表连接关系,只改变链表的值(遍历) 思路 最无脑的思路应该就是建立一个列表,按顺序存入链表中每个node的值; 之后对列表进行倒置; 最后再将倒置后的列表写入一个新的链表。 代码 # Definition for singl..

NLOS的博客 973

PyQt5开发编译器安装(PyCharm安装)

PyCharm 提供了最完整的 PyQt5 开发体验,特别是其集成的调试工具和 Qt Designer 支持,能显著提高开发效率。是最受欢迎和功能最完整的 IDE。它专门为 Python 开发优化,对 PyQt5 有很好的支持。右键运行该文件,如果出现窗口说明配置成功。对于 PyQt5 开发,

啊渊的专栏 423

华为OD机试 - 荒岛求生 - 栈Stack(Python/JS/C/C++ 新系统 100分)

每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天优快云在线答疑。

学Java,找哪吒 2840

LeetCode 817. 链表组件

题目: 给定一个链表(链表结点包含一个整型值)的头结点 head。 同时给定列表 G,该列表是上述链表中整型值的一个子集。 返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。 示例 1: 输入: head: 0-&amp;gt;1-&amp;gt;2-&amp;gt;3 G = [0, 1, 3] 输出: 2 解释: 链表中,0 和 1 是相连接的,且 G...

xiao1guaishou的博客 299

构建AI Agent驱动的智能健康管理系统

数据碎片化:健康数据分散在不同的设备和平台中,难以统一管理和分析。个性化不足:健康管理方案通常是通用的,难以根据个人的健康状况实时调整。用户参与度低:用户难以获得及时、个性化的健康建议,导致健康管理效果不佳。AI Agent是一个能够感知环境、采取行动以实现目标的智能实体。根据智能体的智能水平,可以分为简单反应式智能体和复杂适应式智能体。实时监测健康数据。获取个性化的健康建议。收到健康风险预警。

AI天才研究院 749

剑指 Offer 24. 反转链表

题目: 暴力解法一:可以利用栈来做,先把每一个Node压入栈,再取出放入另一个新链表。 public ListNode reverseList(ListNode head) { if(head == null) { return null; } // 最好别去破坏原链表 ListNode cur = head; // 压入栈 Stack<ListNode> stack

flunggg的博客 241

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【剑指offer】JZ24-反转链表-Python解法

链表反转即将每个结点的指针从向后变为向前,所以最简单的办法就是遍历原始链表,将遇到的结点指针一一逆向即可,但这样做有一个缺陷,如果我们将当前结点原本向后的指针修改为指向前一个结点的指针,那将会造成链表断裂,从后一个结点开始的链表信息丢失。为了弥补这个缺陷,我们应该额外存储下一个结点。具体实现思路如下:1.设置两个指针,一个表示上一个结点的指针(pre,初始值为空),一个表示当前结点的指针(cur);

冲冲冲 672

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

剑指 Offer 24. 反转链表 LCOF

剑指 Offer 第一题

天才小镇刷题家的博客 362

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

【Warrior刷题笔记】剑指offer 6 24 35. 三道题,让你学会链表递归迭代辅助栈

题目一 从尾到头打印链表 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/ 1.描述 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 2.示例 示例 1: 输入:head = [1,3,2] 输出:[2,3,1] 解法一 迭代+辅助栈 解题思路 看到题不难想到最简单的办法就是借助一个辅助栈,顺序遍历将节点值入栈,然后再依次出栈,就能实现倒序打印。

qq_39255924的博客 574

【剑指offer】题型总结 - 链表

剑指offer - 链表

weixin_43736572的博客 670

Leetcode《图解数据结构》刷题日志【第二周】(2022/10/24-2022/10/30)

leetcode《图解数据结构》刷题记录,包括题目思路和java代码

weixin_44201830的博客 936

[剑指offer] 06.从头到尾打印链表& 24.反转链表

个人笔记

han15620的博客 799

offer(第二版)2021-06-02

还差差14个题完结 面试题1:赋值运算符函数 面试题2:实现Singleton模式 面试题3:数组中重复的数字 面试题4:二维数组中的查找 面试题5:替换空格 面试题6:从尾到头打印链表 面试题7:重建二义树 面试题8:二叉树的下一个节点 面试题9:用两个栈实现队列 面试题10:斐波那契数列 面试题11:旋转数组的最小数字 面试题12:矩阵中的路径 。。。 面试题13:机器人的运动范围 。。。 面试题14:剪绳子 。。。 面试题15:二进制中1的个数 面试题16:数值的整数次方 面试题17:打印1到最大的.

qq_43808700的博客 7376

【Leetcode -- 剑指OfferDay02 -- 链表】

力扣上剑指Offer Day02 三道题的刷题记录和题目分析

eee3331的博客 248

剑指offer刷题全纪录

技巧总结: 问清楚问题的条件,比如是否是二叉树,还是二叉搜索树 考虑清楚边界条件,一定要记得判断 考虑清楚数据类型,比如 int 和 long long 传参尽量用引用或指针传递,提高效率 复杂大问题尽量化成小问题分析 1.找出数组中重复的数字 给定一个长度为nn的整数数组nums,数组中所有的数字都在0∼n−10∼n−1的范围内。 数组中某些数字是重复的,但不知道...

向着星辰大海 2379

【刷题记录】剑指offer+Leetcode75 DAY2

。

a462265680的博客 155

《剑指Offer v2》数据结构与算法 题目解法关键知识点记录(一)

《剑指Offer v2》数据结构与算法 题目解法关键知识点记录

u010894131的博客 182

专题:剑指offer

JZ6 从尾到头打印链表思路:先顺序输出到栈里面 然后再以此从栈顶弹出即可 JZ24 反转链表思路:借助虚拟头结点进行头插法 JZ25 合并两个排序的链表方法一:迭代法 方法二 递归: JZ52 两个链表的第一个公共结点方法一:循环遍历两个链表 方法二·:遍历长链表 先快走几步 后面和端链表一起同步走 方法一 方法二 JZ23 链表中环的入口结点 思路:快慢指针 循环体内 快指针每次走两步 慢指针每次走一步 能够相遇也就是说明有环 然后 慢指针从头开始 另外一个指针从相遇节点开始 判断是否再次相遇 不相遇

qq_23923713的博客 656
上一篇: 【链表-简单】剑指 Offer 06. 从尾到头打印链表
下一篇: 【链表-简单】206. 反转链表
菜菜2022
博客等级 码龄9年 67粉丝 1033原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值