/**
* 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 change_len = n-m+1;//需要移动的节点数目
ListNode pre_head = null;//一共需要记录四个节点 第一个
ListNode result = head;
//将head指向当前需要移动的链表段的头
while((head!=null)&&(--m>0)){
pre_head = head;
head = head.next;
}
//将来的链表尾部节点
ListNode modify_list_tail = head;
//逆序部分链表
ListNode new_head = null;
while(head!=null&&(change_len>0)){
ListNode next = head.next;
head.next = new_head;
new_head = head;
head = next;
change_len--;
}
//尾部连上
modify_list_tail.next = head;
//首部连上
//如果m是1 pre_head为空 所以要分类讨论
if(pre_head!=null){
pre_head.next = new_head;
}
else
result = new_head;
return result;
}
}
浙公网安备 33010602011771号