[leetcode] 92. 反转链表 II

92. 反转链表 II

把一个链表部分反转,这个是我经常爱出的面试题,今天终于轮到我做了

我们在25. k个一组翻转链表中处理过类似的问题,那个更难,要求 k 个节点一组进行翻转。这个题相对起来就简单多了,我们可以直接利用那个题的reverse函数.反转一下就可以了。

为了方便,我们有个小trick,需要一个空的头节点指向第一个节点

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;
    }
} 

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9428046.html