思路
- 找到逆置段开始的节点(前一个节点):将head向前移动m-1并且使用modify_tail存储逆置后的尾节点,so easy
- 逆置n-m+1中间段,注意:再次过程中head其实就像个游标完成整个任务而result用来保存最开始head指向的位置。
- 这样,我们其实有了三段链表:result—>pre; new_head—>modify_tail;head–>lastnode; 最后只需要链接即可。
代码
/**
* 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) {
//需要翻转的节点数
int k = n-m+1;
//设置哑节点指向头指针
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = null;
//找开始指针的前一个指针:pre
while(--m!=0){
pre = head;
head = head.next;
}
//需要翻转的开始节点
ListNode modifytail = head;
ListNode newhead = null;
//开始翻转
while(k--!=0){
ListNode save = head.next;
head.next = newhead;
newhead = head;
head = save;
}
//翻转完成,连接第二段和第三段
modifytail.next = head;
//[5] 单个节点判空
if(pre!=null){
pre.next = newhead;
}else{
return newhead;
}
return dummy.next;
}
}