【题目】反转部分单向链表,时间复杂度O(N),空间复杂度O(1)
public class reversePartNode {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
public static Node reversePartNode(Node head, int from, int to) {
Node node1 = head;
Node pre = null;
Node pos = null;
int len = 0;
while (node1 != null) {
len++;
pre = len == from - 1 ? node1 : pre;
pos = len == to + 1 ? node1 : pos;
node1 = node1.next;
}
if (from > to || from < 1 || to > len) {
return head;
}
node1 = pre == null ? head : pre.next;
Node node2 = node1.next;
node1.next = pos;
Node next = null;
while (node2 != pos) {
next = node2.next;
node2.next = node1;
node1 = node2;
node2 = next;
}
if (pre != null) {
pre.next = node1;
return head;
}
return node1;
}
}