Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fec4381

Browse files
updates reverse linked list ii in java
1 parent 6a731d6 commit fec4381

File tree

1 file changed

+32
-41
lines changed

1 file changed

+32
-41
lines changed

β€Žsrc/ReverseLinkedListII.java

Lines changed: 32 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,46 @@
1+
// T: O(n)
2+
// S: O(1)
3+
14
public class ReverseLinkedListII {
2-
private static class ListNode {
5+
public static class ListNode {
36
int val;
47
ListNode next;
8+
ListNode() {}
59
ListNode(int val) { this.val = val; }
6-
7-
@Override
8-
public String toString() {
9-
if (next == null) return "ListNode{val=" + val + ", next=null}";
10-
return "ListNode{" +
11-
"val=" + val +
12-
", next=" + next +
13-
'}';
14-
}
10+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
1511
}
1612

17-
public ListNode reverseBetween(ListNode head, int m, int n) {
18-
if (head == null || m == n) {
19-
return head;
20-
}
13+
public ListNode reverseBetween(ListNode head, int left, int right) {
14+
if (left == right) return head;
2115

22-
// Move the two pointers until they reach the proper starting point
23-
// in the list.
24-
ListNode cur = head, prev = null;
25-
while (m > 1) {
26-
prev = cur;
27-
cur = cur.next;
28-
m--;
29-
n--;
16+
ListNode start = new ListNode();
17+
start.next = head;
18+
19+
ListNode temp = start;
20+
int i = 1;
21+
for ( ; i < left ; i++) {
22+
temp = temp.next;
3023
}
3124

32-
// The two pointers that will fix the final connections.
33-
ListNodecon = prev, tail = cur;
25+
ListNodea = temp.next, b = temp.next.next, c = temp.next.next.next;
26+
a.next = null;
3427

35-
// Iteratively reverse the nodes until n becomes 0.
36-
ListNode third = null;
37-
while (n > 0) {
38-
third = cur.next;
39-
cur.next = prev;
40-
prev = cur;
41-
cur = third;
42-
n--;
28+
for ( ; i < right && c != null; i++) {
29+
b.next = a;
30+
a = b;
31+
b = c;
32+
c = c.next;
4333
}
44-
45-
// Adjust the final connections
46-
if (con != null) {
47-
con.next = prev;
48-
} else {
49-
head = prev;
34+
if (i < right) {
35+
b.next = a;
36+
if (left != 1) {
37+
temp.next = b;
38+
return start.next;
39+
}
40+
return b;
5041
}
51-
52-
tail.next = cur;
53-
return head;
42+
temp.next.next = b;
43+
temp.next = a;
44+
return start.next;
5445
}
5546
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /