92. Reverse Linked List II

Reverse a linked list from positionmton. Do it in-place and in one-pass.

For example:
Given1->2->3->4->5->NULL,m= 2 andn= 4,

return1->4->3->2->5->NULL.

Note:
Givenm,nsatisfy the following condition:
1 ≤m≤n≤ length of list.

tag: linkedlist

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m == n) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;

        for (int i = 0; i < m - 1; i++){
            pre = pre.next;
        }
        ListNode start = pre.next;
        ListNode then = start.next;

        for (int i = 0; i < n - m; i++){
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }

        return dummy.next;   
    }
}

results for ""

    No results matching ""