[LeetCode] 92. Reverse Linked List II
2022/1/12 6:03:26
本文主要是介绍[LeetCode] 92. Reverse Linked List II,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example1:
Input: head = [1,2,3,4,5], left = 2, right = 4 Output: [1,4,3,2,5]
Example2:
Input: head = [5], left = 1, right = 1 Output: [5]
这道题思考很简单,就是找到最开始需要反转的前一个点和第一个点记下来, 然后反转,再把反转的最后一个点以及反转后面的第一个点记下来,最后串联起来。需要注意边界,比如第一个点就是需要反转的点,所以设置一个dummy node会让整个过程简化。
/** * 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) { if (head == null || left >= right || head.next == null) { return head; } //寻找需要反转的第一个点以及之前的点。之前的点用ps记住,第一个点用start记住。注意start不要指向head,要指向ps.next ListNode dummy = new ListNode(0, head); ListNode ps = dummy; int step = right - left + 1; while (--left > 0) { ps = ps.next; head = head.next; } ListNode start = ps.next; ListNode prev = ps; ListNode next = null; //反转需要反转的list,之后prev记住的是反转的最后一个点,head是反转后的第一个点 while (step-- > 0 && head != null) { next = head.next; head.next = prev; prev = head; head = next; } //把该串联的三块串联号 ps.next = prev; start.next = head; return dummy.next; } }
这篇关于[LeetCode] 92. Reverse Linked List II的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享