当前位置:网站首页>92. 反转链表 II-字节跳动高频题
92. 反转链表 II-字节跳动高频题
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
二、解题
链表拆分+合并
先找到上面四个节点值,然后preleft和leftnode断开,然后在将rightnode和nextright断开,然后将leftnode和rightnode中的链表翻转,然后在合并链表。
/** * 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 reverseBetween(ListNode head, int left, int right) {
//定义两个节点,left 的前一个节点,right的后一个节点
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prelfet = dummy;
//查找四个节点
for(int i = 0;i<left-1;i++){
prelfet = prelfet.next;
}
ListNode leftnode = prelfet.next;
ListNode rightnode = prelfet;
for(int i = 0;i<right-left+1;i++){
rightnode = rightnode.next;
}
ListNode nextright = rightnode.next;
//断开链表
prelfet.next = null;
rightnode.next = null;
//翻转链表
ListNode cur = reverse(leftnode);
//合并链表
prelfet.next = cur;
leftnode.next = nextright;
return dummy.next;
}
//翻转链表有两种 递归和迭代
public ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode cur = reverse(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124220472
边栏推荐
猜你喜欢
Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
SiteServer CMS5. 0 Usage Summary
ClickHouse-表引擎
Halo 开源项目学习(二):实体类与数据表
In embedded system, must the program code in flash be moved to ram to run?
JVM类加载机制
Double pointer advanced -- leetcode title -- container with the most water
RPC核心概念理解
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
HCIP第五次实验
随机推荐
Manually implement simple promise and its basic functions
ASP. Net core configuration options (Part 1)
Simulation of infrared wireless communication based on 51 single chip microcomputer
Using quartz under. Net core -- general properties and priority of triggers for [5] jobs and triggers
Further study of data visualization
Generation of barcode and QR code
C语言函数详解
Halo 开源项目学习(二):实体类与数据表
Detailed explanation of C webpai route
Construction of functions in C language programming
Abnormal resolution of Xiaomi camera
Using quartz under. Net core - [1] quick start
Tdan over half
Use of todesk remote control software
Some problems encountered in recent programming 2021 / 9 / 8
ASP. Net core dependency injection service life cycle
El date picker limits the selection range from the current time to two months ago
1-3 components and modules
Why do some people say SCM is simple and I have to learn it so hard?
JS to find the character that appears three times in the string