LeetCode ---- 92、反转链表 II

题目链接

思路:

将链表切为三段,前m - 1个为一段(第一段),第m个到第n个为一段(第二段),剩下的为一段(第三段),将第二段翻转后与第一段和第三段进行拼接即可。

    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || m == n) {
            return head;
        }
        // 创造一个假的头节点,防止m等于1时需要特殊处理
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode preM = dummy;
        ListNode curN = dummy;
        // 找到第m-1个节点
        for (int i = 1; i < m; i++) {
            preM = preM.next;
        }
        // 找到第n个节点
        for (int i = 1; i <= n; i++) {
            curN = curN.next;
        }
        // 第n+1个节点
        ListNode afterN = curN.next;
        // 断链
        curN.next = null;
        // 第m个节点
        ListNode curM = preM.next;
        // 断链
        preM.next = null;
        // 反转第m个节点到第n个节点之间的链表
        reverse(curM, curN);
        // 拼接
        curM.next = afterN;
        preM.next = curN;
        return dummy.next;
    }
    private void reverse(ListNode start, ListNode end) {
        ListNode tmp = null;
        ListNode next = null;
        ListNode cur = start;
        while (cur != end) {
            next = cur.next;
            cur.next = tmp;
            tmp = cur;
            cur = next;
        }
        cur.next = tmp;
    }
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/107290295