第一种方法:比较好理解,将原数组分成三段,然后对中间链表进行反转,最后在拼接上,时间复杂度为O(n),空间复杂度为O(1)。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
//将链表分成三部分
// 0->m-1为一部分,m->n为一部分, n+1->null为一部分
ListNode result = new ListNode(-1);
result.next = head;
//pre一直到m-1个位置
ListNode pre = result;
for (int i = 1; i < m; i++) {
pre = pre.next;
}
//tail一直到第n个位置
ListNode tail = pre;
for (int i = 0; i < n - m + 1; i++) {
tail = tail.next;
}
//这里保存第m个位置的数据和n+1的位置
ListNode revertNode = pre.next;
ListNode end = tail.next;
pre.next = null;
tail.next = null;
revert(revertNode);
pre.next = tail;
revertNode.next = end;
return result.next;
}
private void revert(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
}
}
第二种方法:参考牛客大佬“De梦“,一个个往前移的思想,时间复杂度为O(n),空间复杂度为O(1)。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
ListNode result = new ListNode(-1);
result.next = head;
ListNode pre = result;
//先找到m-1位置
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode temp = null;
ListNode cur = pre.next;
for (int i = 0; i < n - m; i++) {
temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return result.next;
}
}