思路:思路简单,截断中间链表,反转再拼接。
代码:
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
//思路很简单,反转中间部分,再拼接起来。
//为了省去奇奇怪怪的错误,创建一个头节点,避免节点个数太少导致null.next.next
ListNode dummyNode = new ListNode(0, head);
dummyNode.next = head;
//分别保存left和right节点
ListNode pre = dummyNode;
//移动left减一步,由于存在哑节点,移动的步长等于走过的真正节点数,让leftNode指向left前一个节点
for (int i = 0; i < left - 1; i++){
pre = pre.next;
}
ListNode leftNode = pre.next, rightNode = pre;
//让rightNode指向right
for (int i = 0; i < right - left + 1; i++){
rightNode = rightNode.next;
}
//保存right的后一个节点
ListNode succ = rightNode.next;
//切断中间链表
pre.next = null;
rightNode.next = null;
//反转中间链表
reverseListNode(leftNode);
//拼接。最后cur指向了null
pre.next = rightNode;
leftNode.next = succ;
return dummyNode.next;
}
public void reverseListNode(ListNode head){
ListNode cur = head;
ListNode pre = null;
while (cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}
}
复杂度分析:时间0(n),空间o(1)