[leetcode] 206. 反轉鏈表

206. 反轉鏈表html

92. 反轉鏈表 II就順手把這個作了code

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode trick = new ListNode(0);
        trick.next = head;
        reverse(trick, Integer.MAX_VALUE);
        return trick.next;
    }

    // 反轉front(不包括from)其後的k個節點
    private ListNode reverse(ListNode front, int k) {
        ListNode from = front.next;
        if (from == null) return front;
        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;
    }
}
相關文章
相關標籤/搜索