当前位置:网站首页>力扣 206.反转链表--递归解决
力扣 206.反转链表--递归解决
2022-07-29 13:25:00 【洋圏外の彼女】
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例二:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
我们可以把问题看为head节点对应的和后面的链表,依次向下分
由此我们便可以使用递归,从下边的开始,依次进行递归
定义一个新的指针指向此时的节点5,也就是head.next的节点
首先让
head.next.next = head;
再让head的下一个指向空即可完成一个小的链表的反转
head.next = null;
这样依次向上就可以完成链表的反转、
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next ==null){
return head;
}
//定义一个新的节点来接收反转所形成的链表
ListNode newNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return newNode;
}
}
边栏推荐
猜你喜欢
随机推荐
带你了解一下PHP搭建的电商商城系统
1191. 家谱树
企业代码安全防护分类
[Numpy] 创建数组
Project Manager: Not bad!The SSO single sign-on code is written, and the sequence diagram is also drawn?
浅谈如何在渗透测试中快速搞定webshell
The interviewer was stunned by the self-growth of 4 mainstream database IDs in one breath
每日优鲜解散疑云:生鲜电商们苦渡生死劫
如何使用MISRA改进嵌入式编程
Understand the yolov7 network structure
How to merge the code when there is a code conflict in the collaborative development of multiple people?
Research on the thinking and application methods of the frontier of ESI research
grid的使用
JUC阻塞队列-ArrayBlockingQueue
The torch using summary
大一(下)暑假作业
Legendary version adds npc modification, adds npc method and configuration parameter tutorial
程序员入门的第一个程序,打印输出 “ HelloWorld “
human pose estimation-DEKR2021CVPR
系列文章|云原生时代下微服务架构进阶之路 - Boris