11package com .chen .algorithm .znn .linkedlist .test92 ;
22
33import com .chen .algorithm .znn .linkedlist .ListNode ;
4+ import com .chen .api .util .thread .study .chapter2 .t6 .CommonUtils ;
45import org .junit .Test ;
56
7+ import javax .sound .midi .Soundbank ;
8+
69/**
10+ * https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/java-shuang-zhi-zhen-tou-cha-fa-by-mu-yi-cheng-zho/
711 * 92. 反转链表 II
812 * 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
913 * 说明:
1418 *
1519 * @Auther: zhunn
1620 * @Date: 2020/10/24 17:23
17- * @Description: 反转链表二:1-双指针,2-删除结点递推
21+ * @Description: 反转链表二:1-双指针,2-双指针头插法- 删除结点递推(推荐)
1822 */
1923public class Solution {
2024
@@ -63,31 +67,34 @@ public ListNode reverseBetween1(ListNode head, int m, int n) {
6367 }
6468
6569 /**
66- * 2-删除结点递推
70+ * 2-删除结点递推 (推荐)
71+ * curr后面的元素删除,然后添加到pre的后面。也即头插法
6772 *
6873 * @param head
6974 * @param m
7075 * @param n
7176 * @return
7277 */
73- public ListNode reverseBetween2 (ListNode head , int m , int n ) {
78+ public ListNode reverseBetween (ListNode head , int m , int n ) {
7479 if (head == null || head .next == null ) {
7580 return head ;
7681 }
7782
78- ListNode dummy = new ListNode (-1 );
79- dummy .next = head ;
83+ ListNode dummy = new ListNode (-1 , head );
8084 ListNode pre = dummy ;
85+ ListNode curr = dummy .next ;
86+
8187 for (int i = 0 ; i < m - 1 ; i ++) {
8288 pre = pre .next ;
83- head = head .next ;
89+ curr = curr .next ; //将curr移动到第一个要反转的节点的位置上
8490 }
8591
8692 for (int i = m ; i < n ; i ++) {
87- ListNode nextTemp = head .next ;
88- head .next = nextTemp .next ;
89- nextTemp .next = pre .next ;
90- pre .next = nextTemp ;
93+ ListNode removeNode = curr .next ;
94+ curr .next = curr .next .next ; // 删除head后面的元素
95+
96+ removeNode .next = pre .next ; // head后面的元素添加到pre后面
97+ pre .next = removeNode ;
9198 }
9299 return dummy .next ;
93100 }
@@ -109,14 +116,13 @@ public void test() {
109116 l1_5 .next = l1_6 ;
110117 l1_6 .next = l1_7 ;
111118
112- ListNode result = reverseBetween1 (l1_1 , 3 , 6 );
119+ ListNode result = reverseBetween (l1_1 , 3 , 6 );
113120
114- System .out .println (result .val );
115- System .out .println (result .next .val );
116- System .out .println (result .next .next .val );
117- System .out .println (result .next .next .next .val );
118- System .out .println (result .next .next .next .next .val );
119- System .out .println (result .next .next .next .next .next .val );
120- System .out .println (result .next .next .next .next .next .next .val );
121+ ListNode a = result ;
122+ while (a != null ) {
123+ System .out .print (a .val + " " );
124+ a = a .next ;
125+ }
126+ System .out .println ();
121127 }
122128}
0 commit comments