两种方式实现链表反转(图解)

单链表反转两种方法 最近同学介绍了一个lettcode(力扣)OJ给我,个人认为这个网站比母校的oj,杭电oj界面友好很多,题库充足,且支持多种主流语言,很适合闲时刷刷提高算法能力,算法的练习如同内功的修炼,碰到算法问题,经常有一种无力感,只能慢慢总结了。 链表是一种重要的数据结构,因为有递归性质,所以总是难以理解,涉及链表的复杂操作总是感觉一头雾水,看别人的实现代码总是似懂非懂,看完就忘,实际上就是没有理解透彻,特... 阅读详情

两种方式实现链表反转(图解)

循环法

思想:循环将相邻两节点反向。

直接上图
循环图解
看图所示,很明显循环的单位为

  • 标记游标 pre、current、next
  • 将当前节点指向前一节点(反转)
  • 移动游标
  • 重复以上步骤

解释:由于单链表无法从后一节点指向前一节点,故而需要保存前一节点(pre)用于反转的目标节点。

java代码实现

  /**
     * 链表反转
     */
    private static void reverseLinked(Node head) {
        Node pre = head;//第一步:标记游标
        Node current = head.next;//第一步:标记游标
        if (current == null) {
            return;
        }
        Node next = current.next;//第一步:标记游标
        current.next = pre;//第二步:节点反转
        pre.next = null;
        while (next != null) {
            pre = current;//第三步:游标后移
            current = next;
            next = current.next;
            current.next = pre;
        }
    }

看着有点重复代码,稍微改造一下吧:

 /**
     * 链表反转
     */
    private static void reverse(Node node) {
        Node pre = null;
        Node next = null;
        while (node != null) {
            next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
    }

至此,反转结束,主要是通过标记循环节点,反转相邻节点,重复以上步骤。

递归法

递归图解
迭代的思想在于

假设 分步 细化

假设DGreverse的作用就是将给定的链表反转成你想要的样子,然后你需要就是给方法传参。
假设链表就两个节点,则你需要做的就是这样

 if (node == null || node.next == null) {
     return node;
  }
  Node temp = node;//保存头节点
  temp.next.next = node;//反转两节点
  node.next = null;//头节点置为尾节点

然后将假设的部分用递归代替:

Node newNode = DGreverse(node.next);

最终就是下面这样。

java代码实现

 /**
     * 递归方式链表反转
     *
     * @param node
     */
    private static Node DGreverse(Node node) {
        if (node == null || node.next == null) {
            return node;
        }
        Node temp = node;
        Node newNode = DGreverse(node.next);
        temp.next.next = node;
        node.next = null;
        return newNode;
    }

完活后带个值验证一下。不要去想递归是怎么实现的,就假设已经实现了,然后传参实现、验证,done!

思必驰离线语音芯片:智能家居控制的核心引擎 思必驰离线语音芯片TH1520通过本地化语音识别技术,为智能家居带来革命性体验。该芯片具备200-600毫秒的快速响应、75分贝抗噪能力和双核异构设计,显著提升设备交互效率。支持自定义指令和10种音色选择,开发周期缩短至3天,BOM成本降低30%,是智能家居控制的核心引擎。 阅读详情

相关推荐

第4章 本地一键部署(新手首选)

本文介绍了OpenClaw的本地部署方法,特别适合新手用户。部署过程仅需执行一条命令,通过自动脚本完成安装和配置向导。安装完成后,用户可通过终端TUI或Web控制面板验证部署是否成功。文章还提供了常见问题的排查方法,包括端口占用、权限不足、APIKey无效和安装卡顿等情况。整个部署流程简单直观,无需手动修改配置文件,适合快速搭建使用。

eastyuxiao的专栏 202

数据算法之反转链表(五种方法)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。示例:输入:head = [1,2,3,4,5]输出:[5,4,3,2,1]这道题来自力扣的第206题,今天我们尝试使用五种不同的方法来实现链表的反转。

weixin_63834061的博客 6873

ADS许可证配置全攻略:从破解文件放置到环境变量设置(实测有效版)

本文详细介绍了ADS许可证配置的全流程,包括环境准备、全新安装、破解文件部署和环境变量设置等关键步骤。针对常见的安装和授权问题,提供了实测有效的解决方案,帮助工程师快速完成ADS的配置与优化。

websocket5live的博客 392

反转链表的四种方法

分享了原地反转,头插,迭代,递归四种反转链表的方法。

z3551906947的博客 1万+

PlutoSDR驱动安装避坑指南:从设备管理器异常到MATLAB 2023b完美识别

本文是一份详细的PlutoSDR驱动安装与MATLAB 2023b集成排错指南。针对Windows系统下常见的设备管理器异常、驱动兼容性问题,提供了从旧驱动清理、手动指定驱动文件到USB连接稳定性排查的完整解决方案。重点阐述了如何通过离线安装硬件支持包,并利用MATLAB命令进行连接测试与射频信号验证,最终实现设备的完美识别与稳定调用。

weixin_29159441的博客 432

COMSOL新手必看:锂电池仿真从入门到精通的5个实战案例(附模型文件)

本文为COMSOL新手提供锂电池仿真的5个实战案例,涵盖锂枝晶生长模拟、电池热失控预警、SOC估计等效电路模型、电池组液冷系统热管理及SOH衰退模型构建。通过详细步骤和参数设置,帮助用户快速掌握锂电池仿真技术,提升新能源研发效率。附模型文件可直接应用。

wdx01234567的博客 264

【算法】反转链表的四种方法(C语言)

新建链表法,递归,迭代,原地反转。

Patrick_yuxuan的博客 1万+

利用树莓派制作智能音箱

利用树莓派制作智能音箱

qq_61803022的博客 1785

【基础算法】反转链表的三种方法

【基础算法】反转链表的三种方法

4348

flowable工作流看这一篇就够了(基础篇)

接下来我们构建一个非常简单的请假流程,Flowable引擎需要流程定义为BPMN 2.0格式,这是一个业界广泛接受的XML标准。在Flowable术语中,我们将其称为一个流程定义(process definition)。一个流程定义可以启动多个流程实例(process instance)。流程定义可以看做是重复执行流程的蓝图。在这个例子中,流程定义定义了请假的各个步骤,而一个流程实例对应某个雇员提出的一个请假申请。

qq_38196449的博客 2万+

Whisper 模型在嘈杂环境中的表现:降噪与增强技术

本报告系统分析了OpenAI Whisper模型在嘈杂环境中的表现机制,重点揭示其内在降噪能力的技术边界,并结合语音增强(SE)、时频分析等前沿技术提出优化方案。内容覆盖从基础概念(如噪声类型对ASR的影响)到理论框架(模型架构与数学形式化),再到实际应用(端到端部署策略)的全链路分析,同时通过案例研究与可视化工具(如梅尔频谱对比图)降低复杂概念的认知门槛。核心结论指出:Whisper的多语言预训练虽提升了泛化性,但在低信噪比(SNR<5dB)场景下需结合前端降噪或联合训练技术以突破性能瓶颈。

AI 原生应用开发的博客 496

链表实现反转的两种方式详细介绍(图解加代码演示)

链表实现反转的两种方式 要求:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 递归方式 分析

weixin_51790763的博客 1174

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

python 链表反转

图解链表反转 python实现1 头插法 class Solution: def reverseList(self, head: ListNode) -> ListNode: if head==None or head.next==None: return head p= head q ...

lhaniey的博客 988

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 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")

图解单链表反转

本文主要以图的方式,来呈现链表反转推演的具体过程,以助于理解,保持思路的清晰。 主要采用两种方法实现单链表反转: (1)通过循环,通过三个指针对链表进行遍历,并逐个反转; (2)使用递归的方法进行反转。 1.循环反转 废话不多说,先上图: 操作过程: ① 初始化pNext至当前节点的下一个节点,为断链做准备② 判断下一个节点是否为NULL,若为NULL则为尾...

dieyi4398的博客 196

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

【LeetCode题目详解】(二)206.反转链表、876.链表的中间结点

【LeetCode题目详解】(二)206.反转链表、876.链表的中间结点

青色_忘川的博客 1171

【leetcode】刷题总结-链表反转(python版)

比较形象的图解blog:https://blog.csdn.net/feliciafay/article/details/6841115 python代码:https://blog.csdn.net/The__Apollo/article/details/78769400

weixin_42486139的博客 569

图解无头单链表的两种逆置方法

方法一:三指针法 首先,上代码 void pListReversal1(pList *pHead)//反转单链表1:三指针法 { assert(pHead); pList pFast = *pHead; pList pMiddle = *pHead; pList pSlow = NULL; while (pFast) { pFast = pFast->_pNext;...

belongHWL的博客 1530

链表的反转python(数据结构与算法)

题目:反转一个单链表 例如: 输入:2,3,4,5,None 输出:5,4,3,2,None 方法一双指针 步骤:1首先使用两个指针分别指向链表第一个和第二个位置,第二指针nxt保存第二个位置,并建立为None的result, 步骤2,将一个元素指向result,(result的起始值为None),将result(current保存了第一个元素的位置)和curren(nxt已经保存...

qq_33465047的博客 359

反转一个链表c语言

c语言反转一个链表

weixin_52082065的博客 317

LeetCode 206.反转链表

LeetCode 206. 反转链表 定义结点类 public class ListNode{ int val; ListNode next; } 详细图解https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/. 1.前插法 1) 头指针 public ListNodereverse(ListNode head){ ListNod

qq_44977060的博客 136

算法与数据结构之LeetCode——反转一个单链表

反转一个单链表 文章目录反转一个单链表0.前言1.可以用递归方式或者循环1.1 使用循环代码如下:1.2 递归实现如下:2.参考网址 0.前言 具体要求如下: 1.可以用递归方式或者循环 1.1 使用循环代码如下: def reverseList(head): prev = None while head: curr = head head =...

华山论健的博客 372

数据结构——线性表——链表反转

链表反转有两种常见方式。下面从图中详细解释。其中带有部分核心代码,最后上完整代码。 迭代法 //首先定义三个变量 PNODE pre = NULL; PNODE now = pHead->pNext; PNODE next = NULL; next = now->pNext;//先保存下一个节点 now->pNext ...

weixin_30293135的博客 113

206:翻转链表

问题描述 反转一个单链表。 示例 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 思路 经典的数据结构问题。 由于头插法建立单链表是跟输入顺序逆序的,我们可以假定给定的链表是数据来源,重新按照头插法建立一个新链表即可。具体怎...

weixin_41687289的博客 116

《剑指Offer》面试题16:反转链表

《剑指Offer》面试题16:反转链表题目描述    定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。解题思路:    为了正确的反转一个链表,需要调整链表中指针的方向。为了将调整指针这个复杂的过程分析清楚,我们可以借助图形来直观的分析。在图中所示的链表中,h,i,j是3个相邻的结点。假设经过若干的操作,我们已经把结点h之前的指针调整完毕,这些结点的m_pNext都指向前面...

南方有乔木的博客 223

图解链表反转系列Leetcode

链表反转系列

code120302的博客 1002
下一篇: 合并两个有序单链表(java实现)
image_2012
博客等级 码龄10年 373粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值