题目链接
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
int count = 1;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
//找到left的前驱
while(pre.next != null && count < left) {
pre = pre.next;
count++;
}
//left开始反转
ListNode cur = pre.next;
//头插法
for(int i = 0; i < right - left; i++) {
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return dummy.next;
}
}