-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_Linked_List_II.java
More file actions
42 lines (39 loc) · 1.11 KB
/
Reverse_Linked_List_II.java
File metadata and controls
42 lines (39 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.leet_code;
public class Reverse_Linked_List_II {
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; }
}
public ListNode reverseBetween(ListNode head, int left, int right) {
if (left == right) {
return head;
}
ListNode current = head;
ListNode prev = null;
for (int i = 0; current != null && i < left - 1; i++) {
prev = current;
current = current.next;
}
ListNode last = prev;
ListNode newEnd = current;
ListNode next = current.next;
for (int i = 0; current != null && i < right - left + 1; i++) {
current.next = prev;
prev = current;
current = next;
if (next != null) {
next = next.next;
}
}
if (last != null) {
last.next = prev;
} else {
head = prev;
}
newEnd.next = current;
return head;
}
}