|
| 1 | +public class ReverseLinkedListII { |
| 2 | + private static class ListNode { |
| 3 | + int val; |
| 4 | + ListNode next; |
| 5 | + ListNode(int val) { this.val = val; } |
| 6 | + } |
| 7 | + |
| 8 | + public ListNode reverseBetween(ListNode head, int leftVal, int rightVal) { |
| 9 | + if (leftVal == rightVal) return head; |
| 10 | + |
| 11 | + ListNode sentinelHead = new ListNode(-1000); |
| 12 | + sentinelHead.next = head; |
| 13 | + ListNode beforeLeft = getNodeBefore(sentinelHead, leftVal); |
| 14 | + System.out.println(beforeLeft.val); |
| 15 | + ListNode left = beforeLeft.next; |
| 16 | +// ListNode afterRight = getNodeAfter(sentinelHead, rightVal); |
| 17 | + ListNode a = beforeLeft.next, b = a.next, c = b.next; |
| 18 | + |
| 19 | + while (c != null && b.val != rightVal) { |
| 20 | + a.next = null; |
| 21 | + b.next = a; |
| 22 | + a = b; |
| 23 | + b = c; |
| 24 | + c = c.next; |
| 25 | + } |
| 26 | + a.next = null; |
| 27 | + b.next = a; |
| 28 | + beforeLeft.next = b; |
| 29 | + left.next = c; |
| 30 | + return sentinelHead.next; |
| 31 | + } |
| 32 | + |
| 33 | + private ListNode getNodeBefore(ListNode head, int value) { |
| 34 | + while (head != null && head.next != null && head.next.val != value) { |
| 35 | + head = head.next; |
| 36 | + } |
| 37 | + return head; |
| 38 | + } |
| 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 | + } |
| 46 | +} |
0 commit comments