class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode pre = null, now = head;
int cnt = 0;
ListNode start = null, end = null;
while(now != null){
cnt++;
ListNode temp = now.next;
if(cnt == left){
start = now;
now.next = pre;
}else if(cnt == right+1){
if(start.next != null){
start.next.next = pre;
start.next = now;
}else{
start.next = now;
head = pre;
}
return head;
}else if(cnt > left && cnt <= right){
now.next = pre;
}
pre = now;
now = temp;
}
if(cnt == right){
if(start.next != null){
start.next.next = pre;
start.next = null;
}else{
start.next = null;
head = pre;
}
}
return head;
}
}
/**
* 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) {
ListNode vnode = new ListNode(-1);//虚拟结点
vnode.next = head;
ListNode pre = vnode;
//让pre指向翻转区间的前一个结点
for(int i=0; i<left-1; i++){
pre = pre.next;
}
ListNode current = pre.next;
//依次翻转区间的结点,不断把下一个结点移动到开始区间的第一个位置
for(int i=0; i<right - left; i++){
ListNode temp = current.next;
current.next = temp.next;
temp.next = pre.next;
pre.next = temp;//注意以上两行不能写成pre.next = temp; temp.next = current;因为这里的current不一定是最接近起始点的位置,current会改变的
}
return vnode.next;
}
}
原文:https://www.cnblogs.com/GarrettWale/p/14539907.html