You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Attempt 1: Use an array to save the reversed nodes
classSolution {
publicListNodereverseBetween(ListNodehead, intleft, intright) {
// Reverse one nodeif (left == right) {
returnhead;
}
// Create a dummy headListNodedummy = newListNode(0, head);
// Create an array to save the reversed nodesintsize = right - left + 1;
ListNode[] saved = newListNode[size];
// Get the node before the reversed nodesListNodecurr1 = dummy;
for (inti = 0; i < left - 1; i++) {
curr1 = curr1.next;
}
// Save the reversed nodes and get the node points to after the reversed nodeListNodecurr2 = curr1.next;
for (inti = 0; i < size; i++) {
saved[i] = curr2;
curr2 = curr2.next;
}
// Connect the reversed nodesfor (inti = size - 1; i >= 1; i--) {
saved[i].next = saved[i - 1];
}
curr1.next = saved[size - 1];
saved[0].next = curr2;
returndummy.next;
}
}