53 lines
1.3 KiB
Java
53 lines
1.3 KiB
Java
package com.zerroi.leetcode.Three24;
|
|
|
|
public class ReverseBetween {
|
|
public static void main(String[] args) {
|
|
|
|
}
|
|
}
|
|
|
|
class ListNode {
|
|
int val;
|
|
ListNode next;
|
|
ListNode() {}
|
|
ListNode(int val) { this.val = val; }
|
|
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
|
|
}
|
|
|
|
class Solution {
|
|
public ListNode reverseBetween(ListNode head, int left, int right) {
|
|
if (left == right) return head;
|
|
ListNode dummy1 = new ListNode(-1);
|
|
ListNode dummy2 = new ListNode(-1);
|
|
ListNode cur1 = dummy1;
|
|
ListNode cur2 = dummy2;
|
|
for (int i = 0; i < left - 1; i++) {
|
|
cur1.next = new ListNode(head.val);
|
|
cur1 = cur1.next;
|
|
head = head.next;
|
|
}
|
|
for (int i = left; i <= right; i++) {
|
|
cur2.next = new ListNode(head.val);
|
|
cur2 = cur2.next;
|
|
head = head.next;
|
|
}
|
|
ListNode reversed = reverse(dummy2.next);
|
|
cur1.next = reversed;
|
|
cur2.next = head;
|
|
return dummy1.next;
|
|
|
|
}
|
|
private ListNode reverse(ListNode head) {
|
|
ListNode pre = null;
|
|
ListNode cur = head;
|
|
ListNode temp;
|
|
while (cur != null) {
|
|
temp = cur.next;
|
|
cur.next = pre;
|
|
pre = cur;
|
|
cur = temp;
|
|
}
|
|
return pre;
|
|
}
|
|
}
|