[leetcode] 92. 反轉鏈表 II

92. 反轉鏈表 IIhtml

把一個鏈表部分反轉,這個是我常常愛出的面試題,今天終於輪到我作了面試

咱們在25. k個一組翻轉鏈表中處理過相似的問題,那個更難,要求 k 個節點一組進行翻轉。這個題相對起來就簡單多了,咱們能夠直接利用那個題的reverse函數.反轉一下就能夠了。函數

爲了方便,咱們有個小trick,須要一個空的頭節點指向第一個節點code

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode trick = new ListNode(0);
        trick.next = head;
        ListNode p = trick;
        int k = 1;
        while (k < m) {
            p = p.next;
            k++;
        }

        reverse(p, n - m + 1);
        return trick.next;
    }

    // 反轉front(不包括from)其後的k個節點
    private ListNode reverse(ListNode front, int k) {
        ListNode from = front.next;
        if (from == null) return front;//相比較25題,這個須要多一個判斷
        ListNode head = from;
        ListNode cur = from.next;
        ListNode tmp = null;
        while (k > 1 && cur != null) {
            tmp = cur.next;
            cur.next = from;

            from = cur;
            cur = tmp;
            k--;
        }
        head.next = cur;
        front.next = from;
        return head;
    }
}
相關文章
相關標籤/搜索