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 2e8e399

Browse files
a
1 parent 7fa5ba1 commit 2e8e399

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

‎src/ReverseLinkedListII.java

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,34 @@ private static class ListNode {
33
int val;
44
ListNode next;
55
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+
}
15+
}
16+
17+
public static void main(String[] args) {
18+
ListNode head = new ListNode(1);
19+
head.next = new ListNode(2);
20+
head.next.next = new ListNode(3);
21+
head.next.next.next = new ListNode(4);
22+
head.next.next.next.next = new ListNode(5);
23+
System.out.println(reverseBetween(head, 2, 4));
624
}
725

8-
public ListNode reverseBetween(ListNode head, int leftVal, int rightVal) {
26+
public staticListNode reverseBetween(ListNode head, int leftVal, int rightVal) {
927
if (leftVal == rightVal) return head;
1028

1129
ListNode sentinelHead = new ListNode(-1000);
1230
sentinelHead.next = head;
1331
ListNode beforeLeft = getNodeBefore(sentinelHead, leftVal);
1432
System.out.println(beforeLeft.val);
1533
ListNode left = beforeLeft.next;
16-
// ListNode afterRight = getNodeAfter(sentinelHead, rightVal);
1734
ListNode a = beforeLeft.next, b = a.next, c = b.next;
1835

1936
while (c != null && b.val != rightVal) {
@@ -23,24 +40,16 @@ public ListNode reverseBetween(ListNode head, int leftVal, int rightVal) {
2340
b = c;
2441
c = c.next;
2542
}
26-
a.next = null;
2743
b.next = a;
2844
beforeLeft.next = b;
2945
left.next = c;
3046
return sentinelHead.next;
3147
}
3248

33-
private ListNode getNodeBefore(ListNode head, int value) {
49+
private staticListNode getNodeBefore(ListNode head, int value) {
3450
while (head != null && head.next != null && head.next.val != value) {
3551
head = head.next;
3652
}
3753
return head;
3854
}
39-
40-
private ListNode getNodeAfter(ListNode head, int value) {
41-
while (head != null && head.val != value) {
42-
head = head.next;
43-
}
44-
return head.next;
45-
}
4655
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /