题目地址:
描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1\to 2 \to 3 \to 4 \to 5 \to NULL1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1\to 4\to 3\to 2\to 5\to NULL1→4→3→2→5→NULL.
数据范围: 链表长度 0 < size \le 10000<size≤1000,0 < m \le n \le size0<m≤n≤size,链表中每个节点的值满足 |val| \le 1000∣val∣≤1000
要求:时间复杂度 O(n)O(n) ,空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)
示例1
输入:
{1,2,3,4,5},2,4
复制返回值:
{1,4,3,2,5}
复制
示例2
输入:
{5},1,1
复制返回值:
{5}
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) {
if(m==n){
return head;
}
ListNode newHead = head;
//记录m-1 和 n+1
int i = 1;
ListNode m1 = null;
ListNode n1 = null;
ListNode mNode = null;
while (head.next != null) {
if(m==1&&i==1){
m1 = null;
mNode = head;
}
if (i == m - 1) {
m1 = head;
mNode = head.next;
};
// 翻转
if(i==m){
ListNode pre = null;
ListNode cur = head;
while(i<=n){
ListNode cur_next = cur.next;
cur.next= pre;
pre = cur;
cur = cur_next;
i++;
}
n1 = cur;
head = pre;
i--;
}
if(i==n){
m1.next = head;
mNode.next = n1;
}
i++;
if (head.next != null) {
head = head.next;
}
}
if(m==1){
newHead = head;
}
return newHead;
}
}