类似每k个节点反转的题
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) {
if (head == null) {
return head;
}
if (m >= n) {
return head;
}
ListNode temp = head;
int len = 0;
while (temp != null) {
len++;
temp = temp.next;
}
ListNode headNode = new ListNode(-1);
headNode.next = head;
ListNode tempHeadNode = headNode;
ListNode curNode = head;
ListNode nextNode = null;
for (int i = 0; i < len; i++) {
if (i == m-1) {
for (int j = 0; j < (n-m); j++) {
nextNode = curNode.next;
curNode.next = nextNode.next;
nextNode.next = tempHeadNode.next;
tempHeadNode.next = nextNode;
}
break;
}
tempHeadNode = curNode;
curNode = curNode.next;
}
return headNode.next;
}
}


京公网安备 11010502036488号