我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
题目描述:
知识点:链表
思路一:递归实现
本题只是在LeetCode206——反转链表的基础上外加了一个寻找待反转子链表的第一个节点的前一个节点以及最后一个节点的过程而已。根据LeetCode206——反转链表的思路,有递归实现和非递归实现两种方法。
由于涉及到递归,而每一次递归的时间复杂度都是O(1)级别的,因此时间复杂度和空间复杂度都是O(n - m)。
JAVA代码:
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur1 = dummyHead;
int interval = n - m;
while(m > 1){
m--;
cur1 = cur1.next;
}
ListNode cur2 = cur1.next;
while(interval > 0){
interval--;
cur2 = cur2.next;
}
ListNode temp1 = cur1.next;
ListNode temp2 = cur2.next;
cur2.next = null;
cur1.next = reverse(temp1);
temp1.next = temp2;
return dummyHead.next;
}
private ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode newHead = reverse(head.next);
ListNode temp = head.next;
temp.next = head;
head.next = null;
return newHead;
}
}
LeetCode解题报告:
思路二:非递归实现
寻找待反转子链表的第一个节点的前一个节点以及最后一个节点的过程与思路一相同,反转链表的过程与LeetCode206——反转链表中的非递归实现相同。
时间复杂度是O(m - n),空间复杂度是O(1)。
JAVA代码:
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur1 = dummyHead;
int interval = n - m;
while(m > 1){
m--;
cur1 = cur1.next;
}
ListNode cur2 = cur1.next;
while(interval > 0){
interval--;
cur2 = cur2.next;
}
ListNode temp1 = cur1.next;
ListNode temp2 = cur2.next;
cur2.next = null;
cur1.next = reverse(temp1);
temp1.next = temp2;
return dummyHead.next;
}
private ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur1 = dummyHead;
ListNode cur2 = dummyHead.next;
ListNode cur3 = cur2.next;
while(cur3 != null){
cur2.next = cur3.next;
ListNode temp = cur1.next;
cur1.next = cur3;
cur3.next = temp;
cur3 = cur2.next;
}
return dummyHead.next;
}
}
LeetCode解题报告: