[leetcode] 206. 反转链表

206. 反转链表

92. 反转链表 II就顺手把这个做了

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;
    }
}
posted @ 2018-08-06 00:36 ACBingo 阅读(...) 评论(...) 编辑 收藏