Untitled

 avatar
unknown
plain_text
12 days ago
2.5 kB
3
Indexable
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 class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || left == right) {
            return head;
        }

        // Create a dummy node to handle cases where left = 1
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;

        // Move prev to the node just before the left position
        for (int i = 1; i < left; i++) {
            prev = prev.next;
        }

        // Start of the sublist to be reversed
        ListNode start = prev.next;

        // Move to the right position and disconnect the sublist
        ListNode end = start;
        for (int i = left; i < right; i++) {
            end = end.next;
        }
        ListNode next = end.next; // Save the node after the sublist
        end.next = null; // Disconnect the sublist

        // Reverse the sublist using recursion
        ListNode newHead = reverseList(start);

        // Reconnect the reversed sublist
        prev.next = newHead;
        start.next = next;

        return dummy.next;
    }

    // Recursive function to reverse a linked list
    private ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    // Helper method to print the linked list
    public static void printList(ListNode head) {
        ListNode curr = head;
        while (curr != null) {
            System.out.print(curr.val + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Example 1
        ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        Solution solution = new Solution();
        ListNode result1 = solution.reverseBetween(head1, 2, 4);
        printList(result1); // Output: 1 4 3 2 5

        // Example 2
        ListNode head2 = new ListNode(5);
        ListNode result2 = solution.reverseBetween(head2, 1, 1);
        printList(result2); // Output: 5
    }
}
Leave a Comment