当前位置:网站首页>LeetCode points to Offer 24. Reverse linked list
LeetCode points to Offer 24. Reverse linked list
2022-08-07 06:25:00 【A rod.】
topic description
Define a function that takes as input the head node of a linked list, reverses the linked list and outputs the head node of the reversed linked list.
Sample
Input: 1->2->3->4->5->NULLOutput: 5->4->3->2->1->NULLQuestion link
https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/
Solution ideas
My idea for this question is to use the head insertion method, that is, each insertion is placed at the head node of the linked list, so that you can go backwards while inserting, and you don't need to maintain other variables, which is very suitable for this problem..
Complexity Analysis
Time complexity: O(n), where n is the length of the linked list.Need to traverse the linked list once.
Space complexity: O(1).
Code

Java code:
class Solution {public ListNode reverseList(ListNode head) {// This question uses tail insertionListNode myHead = new ListNode();while (head != null) {ListNode node = new ListNode(head.val);// Don't let the list breaknode.next = myHead.next;myHead.next = node;head = head.next;}// My head node here is empty, so return nextreturn myHead.next;}}边栏推荐
猜你喜欢
随机推荐
pytest框架之fixture测试夹具详解
The spyder/conda installation package reports an error: conda info could not be constructed. KeyError: 'pkgs_dirs'
案例:搭建Zabbix监控系统
leetcode 110. 平衡二叉树
servlet tutorial 1: environment setup and new servlet project
R语言结合并行计算的实例一文讲懂环境
剑指 Offer II 091. 粉刷房子
mysql获取近7天,7周,7月,7年日期,根据当前时间获取近7天,7周,7月,7年日期
微信支付学习笔记
@Async注解的使用方法
The permutation sequence of the 60th question in C language.Breadth-first search, simple division positioning
js中blob转string、string转blob、typeArray转blob、blob转TypeArray
MySQL - 索引优化
程序员福音,关于如何使用Markdown写出一份漂亮的简历 —— 程序员简历 | md文档简历制作教程
机器学习案例之客户的信用风险与预测
10年经验总结:数据分析师7种工具,因果分析划重点!
OS模块中获取当前文件的绝对路径的相关方法
DOM,SAX,JDOM,DOM4J四种方法对比总结
R语言sys函数系列(一)
Codeforces暑期训练周报(7.28~8.3)









