反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。

Richal發表於2018-09-07
public static ListNode reverseBetween(ListNode head, int m, int n) {
    if (head == null || head.next == null) return head;
    ListNode start = null;
    ListNode end = null;
    ListNode cur = head;
    ListNode prev = null;
    ListNode temp;
    if (m == n || m > n) return head;
    if (m > 1) {
        for (int i = 1; i < m; i++) {
            start = cur;
            cur = start.next;
            end = cur;
        }
    }
    for (int i = m; i <= n; i++) {
        temp = cur.next;
        cur.next = prev;
        prev = cur;
        cur = temp;
    }
    if (m==1) {
        head.next = cur;
        return prev;
    }
    end.next = cur;
    start.next = prev;
    return head;
}複製程式碼


相關文章