描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n),空间复杂度 O(1)。
例如:
给出的链表为 1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1→4→3→2→5→NULL.
示例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) {
// write code here
if(head==null){
return head;
}
//加个表头
ListNode res = new ListNode(-1);
res.next = head;
ListNode pre=res;
//循环到需要反转的起始位置
for(int i=0;i<m-1;i++){
pre=pre.next;
}
//定义子链表
ListNode rightNode=pre;
for(int i=0;i<n-m+1;i++){
rightNode=rightNode.next;
}
//取子链表的头结点
ListNode leftNode=pre.next;
//后置结点
ListNode cur=rightNode.next;
pre.next=null;
rightNode.next=null;
//反转链表
reverseLinkedList(leftNode);
//拼接子链表
pre.next=rightNode;
leftNode.next=cur;
return res.next;
}
//反转链表
private void reverseLinkedList(ListNode head){
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
}
}