Description
https://leetcode.com/problems/reverse-linked-list-ii/
将链表第m个结点至第n个结点的部分反转,要求只扫描一遍链表
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
Solving Ideas
partOneTail
: 表示第m个结点的前一个结点,当m == 1
时,partOneTail == null
i >= m && i <= n
时,对该部分进行反转,操作与Reverse Linked List类似
反转后,prev
指向原链表第n个结点,cur
指向原链表第n个结点的下一个结点,此时需要:
- 将反转部分的尾部(原链表第m个结点)指向
cur
(原链表第n个结点的下一个结点) - 当
partOneTail != null
时,使partOneTail
指向反转部分的头部(原链表第n个结点);否则反转部分的头部成为整个链表新的头结点
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null) return head;
ListNode partOneTail = null, prev = null, cur = head;
for (int i = 1; i <= n; i++) {
if (i == m - 1) partOneTail = cur;
if (i >= m) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
} else {
cur = cur.next;
}
}
if (partOneTail == null) {
head.next = cur;
return prev;
}
partOneTail.next.next = cur;
partOneTail.next = prev;
return head;
}
}