反转链表(迭代)-基于python

python递归&迭代方法实现链表反转 这篇文章主要介绍了python递归&迭代方法实现链表反转,文章分享一段详细实现代码,需要的小伙伴可以参考一下,希望对你的学习或工作有所帮助。reverse = reverse_list(head.next) #假设reverse是head以后的、已经反转过的链表。print_list(head) #发现此时head节点变成了最后一个节点,说明函数是对head这个实例直接作用的。print('反转一次的list:')print('反转两次的list:')print('原始list:') 阅读详情

题目描述

输入一个链表,反转链表后,输出新链表的表头。

反转链表是面试的基础题,掌握是很有必要的。

我们采用迭代思想进行链表反转

首先我们定义三个指针,分别表示前一个节点pre,当前节点cur,中间节点temp

每次循环时使得当前节点指向前一节点,然后节点后移进行下一反转。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead:return None
        pre = pHead
        cur = pHead.next
        temp = None
        while cur:
            temp = cur.next  # temp记录下一节点位置
            cur.next = pre   #当前节点指向前一节点
            pre = cur  #指针后移
            cur = temp   #指针后移
        pHead.next = None   #原头结点指向None
        return pre

 

Python实现链表反转的方法分析【迭代法与递归法】 head.next.next = head # 当前层函数的head节点的后续节点指向当前head节点。cur_node.next = new_link # cur_node指向new_link。new_link = cur_node # 反转链表更新,cur_node为新的头结点。tmp = cur_node.next # cur_node后续节点传递给中间变量。new_link = None # 表示反转后的链表。cur_node = head # 当前节点。 阅读详情

相关推荐

【第六届起重机创意大赛国一作品——资料分享】

文章目录前言一、比赛内容分析二、确定方案与作品模型1.方案简图2.作品模型三、电控部分控制思路单片机选择与资源分配拓展板的设计接线与走线代码分享总结

qq_19308801的博客 7791

反转链表-迭代反转法

反转链表,又可以称为翻转或逆置链表,如图常用的实现方案有4种,这里分别将它们称为迭代反转法、递归反转法、就地逆置法和头插法。值得一提的是,递归反转法更适用于反转不带头节点的链表;其它3种方法既能反转不带头节点的链表,也能反转带头节点的链表。......

有朋自远方来,不亦乐乎。 1335

从零搭建Obsidian智能知识库:Ollama本地模型与Copilot插件实战指南

本文详细介绍了如何从零搭建Obsidian智能知识库,结合Ollama本地模型与Copilot插件实现高效知识管理。通过本地部署AI助手,用户可以在保证隐私安全的同时,快速检索和整理笔记,提升工作效率。文章涵盖硬件准备、Ollama部署、插件配置及实战技巧,适合需要高效知识管理的专业人士。

weixin_29230773的博客 632

反转链表(迭代)

首先,反转链表就是将节点的 next 域从 存储下一节点地址 变成 存储上一节点地址,就可以实现链表反转 像这样, 变为这样, 但是,单向链表是不存储前驱节点的,所以 第一步,我们要先定义一个空节点作为新链表的头节点,再将原链表的头节点定义一个节点cur; 第二步,将第一个节点的next域内地址记录下来,记作cur_next; 第三步,将新链表的头节点pre的值给到cur节点的next域 第四步,将新链表的头节点pre移动到原链表的头节点cur的位置; 第五步,将cur移动到

weixin_44867820的博客 677

ETAP实战:如何用仿真软件快速绘制标准一次接线图(附模板下载)

本文提供了一套基于ETAP软件高效绘制标准一次接线图的完整实战工作流。从国标符号库配置、绘图模板创建,到核心设备绘制、参数标注,再到利用软件模型进行拓扑检查与短路电流校核,手把手教你实现从零到一的专业图纸设计。文末附有实用模板下载,助你大幅提升电力设计效率与图纸质量。

weixin_29291573的博客 523

Halcon 3D视觉实战:5步将线激光高度数据转为可分析的深度图与点云

本文详细介绍了如何利用Halcon平台将线激光高度数据转换为深度图与点云的5步实战方法。通过具体代码示例和工业检测案例(如锂电池胶水测量),帮助工程师高效处理3D视觉数据,实现从原始数据到三维可视化的完整技术链路。

weixin_29039773的博客 367

【算法练习】4种反转链表的方法(Java实现)

几种链表反转方法的主要区别在于迭代法和递归法是在原链表上直接反转,无需额外空间;而头插法和栈辅助需要 O(N) 的额外空间。一般迭代法代码最简洁,递归法需要处理终止条件,但思路清晰。

软件工程探索之旅 6716

三、Crowd与JIRA、Confluence用户集成并SSO单点登录

补充说明: 通过此方法集成后,用户、组以及用户和组的关系都在Crowd系统中存储,但各个系统的权限仍由各系统控制,也可在JIRA和Confluence中添加和删除用户。 在做步骤4和步骤5的时候,要特别小心,确保当前系统的超级权限用户(一般为admin,具体看当前系统的全局权限配置)和组以及它们的关系已经在Crowd中同样存在了,才可切换并禁用当前系统的内部用户目录,否则可能造成权限丢失等严重问题(因为禁用了内部用户目录,而Crowd中又不存在这个超级权限用户和组或它们的关系,所以权限就丢失了) 维护示例

weixin_38621072的博客 2995

反转链表的Java实现

目录 1、迭代法 2、递归方式 反转链表: 输入:1->2->3->4->5 输出:5->4->3->2->1 1、迭代法 思路:遍历整个链表,当链表不为空时,每次取链表的第一个Node作为当前节点,修改当前Node的指针,重复此步骤,步骤解析如下: Java代码的具体实现步骤 public static ListNode reverseNode_1(ListNode node) { ListNode previ

swadian2008的博客 6799

b站视频链接快速获取

快速获取b站视频数据

qq_45889931的博客 8335

Unity-Mirror网络框架-从入门到精通之MultipleMatches示例

Multiple Matches 示例主要讲述了如何在使用 Mirror 网路框架时管理多个游戏匹配。以及如何设置一个能够同时支持多个游戏会话的系统,使玩家能够加入他们所选择的比赛,而不是强制他们加入一个单一的匹配。

TxNet 970

反转链表(java)

题目: 给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。 数据范围: 0\leq n\leq10000≤n≤1000 要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。 如当输入链表{1,2,3}时, 经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1} 以上转换过程如下图所示: 解题思路:迭代法 1.定义两个临时变量,一个preNode:用于存放前一个节点,先...

java_smallwrite的博客 7643

Spark Sql 连接mysql

转载请务必注明原创地址为:http://dongkelun.com/2018/03/21/sparkMysql/ 1、基本概念和用法(摘自spark官方文档中文版) Spark SQL 还有一个能够使用 JDBC 从其他数据库读取数据的数据源。当使用 JDBC 访问其它数据库时,应该首选 JdbcRDD。这是因为结果是以数据框(DataFrame)返回的,且这样 Spark SQL操作轻松或便......

主要分享大数据相关的知识,如Spark、Hudi 1万+

Python实现链表反转(迭代法与递归法)

Python实现链表反转 链表反转(while迭代实现): 链表的反转引入一个cur_node变量,表示当前节点;同时需要引入一个变量new_link表示反转后的新链表;while循环内还需中间变量tmp存放当前节点的后继节点,防止原链表数据丢失。 在while循环内(循环条件为 cur_node !=None,若设置为cur_node.next将导致最后一个节点无法反转到新链表): 首...

one_Salted_FishGG的博客 4374

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

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

Python实现链表反转:迭代与递归双解法详解

本文详解链表反转的两种经典实现方法——迭代法和递归法,提供Python代码逐行解析,并对比两种方法的性能差异与应用场景。

2501_90618844的博客 1740

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

python实现链表反转_Python实现链表反转的方法分析【迭代法与递归法】

本文实例讲述了Python实现链表反转的方法。分享给大家供大家参考,具体如下:Python实现链表反转链表反转(while迭代实现):链表的反转引入一个cur_node变量,表示当前节点;同时需要引入一个变量new_link表示反转后的新链表;while循环内还需中间变量tmp存放当前节点的后继节点,防止原链表数据丢失。在while循环内(循环条件为 cur_node !=None,若设置为cur...

weixin_39630880的博客 133

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

python实现链表的反转递归_Python实现链表反转的方法分析【迭代法与递归法】

本文实例讲述了Python实现链表反转的方法。分享给大家供大家参考,具体如下:Python实现链表反转链表反转(while迭代实现):链表的反转引入一个cur_node变量,表示当前节点;同时需要引入一个变量new_link表示反转后的新链表;while循环内还需中间变量tmp存放当前节点的后继节点,防止原链表数据丢失。在while循环内(循环条件为 cur_node !=None,若设置为cur...

weixin_29868343的博客 389

翻转链表python递归_Python实现链表反转的方法【迭代法与递归法】

导读这篇文章主要介绍了Python实现链表反转的方法,结合实例形式分析了Python迭代法与递归法实现链表反转的相关操作技巧与注意事项,需要的朋友可以参考下本文实例讲述了Python实现链表反转的方法。分享给大家供大家参考,具体如下:Python实现链表反转链表反转(while迭代实现):•链表的反转引入一个cur_node变量,表示当前节点;同时需要引入一个变量new_link表示反转后的新链表...

weixin_39720181的博客 121

LeetCode题目92:反转链表ll 【python 递归与迭代方法全解析】

本文详细讨论了链表反转的三种方法:迭代、全递归和局部递归,提供了代码实现,并比较了它们的效率和适用场景。

10年数据\经营分析经验,现任大厂数据分析负责人 533

leetcode第206题python版反转链表_迭代法

206. 反转链表 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode)

前端帅小伙 311

使用python实现链表的基本结构并对链表进行反转(使用迭代和递归两种方式),加上一些个人理解(python并行赋值等)

链表是一种较为常用的数据结构,本文简单介绍了链表,以及如何使用python实现基础的链表,之后再完成对链表的反转。最后对这个过程中产生的一些问题如链表的储存,python的行内多项赋值 做了解析。

keepaware的博客 1520

Python3--反转链表之迭代,递归,穿针引线(头插法)

递归法 反转链表1 class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # 递归终止条件是当前为空,或者下一个节点为空 if(head==None or head.next==None): return head # 这里的cur就是最后一个节点 cur = self.reverseList(head.next) #

weixin_45511236的博客 371

[LeetCode-Python版]206. 反转链表(迭代+递归两种解法)

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

m0_69281817的博客 695

leetcode 206 Reserve Linked List(反转链表) python3 递归&迭代思路

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

Jasmine_dream 1178

python反转链表(递归&迭代)

#定义链表node结构 class ListNode: def __init__(self,data): self.data = data self.next = None #将L转化为链表 def make_list(L): #将L初始化为链表 head = ListNode(L[0]) cur = head for i in L[1:]: cur.next = ListNode(i) cur .

包龙星的剑 2070
上一篇: 二维数组中的查找 and 搜索二维矩阵 II - 基于python
下一篇: 合并排序链表 - 基于python
心之所向丶7
博客等级 码龄11年 17粉丝 59原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址