Leetcode 92. Reverse Linked List II

Posted Deribs4

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

思路:添加头节点,反转链表某个连续部分,206. Reverse Linked List是本题的特殊情况,也可以像本题一样做,具体见Leetcode 206. Reverse Linked List

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode reverseBetween(ListNode head, int m, int n) {
11         if(head == null) return head;
12         ListNode dummy = new ListNode(0);
13         dummy.next = head;
14         ListNode pre = dummy;
15         for(int i = 0; i < m - 1; i++) pre = pre.next;//移动m-1次
16         ListNode start = pre.next;
17         ListNode then = start.next;
18         for(int i = 0; i < n - m; i++) {//需要将start后面的n-m个点陆续反转
19             start.next = then.next;//start的后面指向then的后面
20             then.next = pre.next;//then的后面指向pre的后面,相当于将then插入pre和pre.next之间
21             pre.next = then;//pre的后面是then
22             then = start.next;//完成一个元素的反转后,then指向下一个准备被反转(插入pre和pre.next之间)的节点
23         }
24         return dummy.next;
25     }
26 }

 

Next challenges: Swap Nodes in Pairs Remove Duplicates from Sorted List II Delete Node in a Linked List

Next challenges: Reverse Nodes in k-Group Linked List Cycle II Intersection of Two Linked Lists

以上是关于Leetcode 92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode92]Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

Leetcode 92. Reverse Linked List II

leetcode.92. Reverse Linked List II

[LeetCode]92. Reverse Linked List II

LeetCode 92. Reverse Linked List II