🌗 92. 反转链表 II

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

🌗 92. 反转链表 II

难度: 🌗

问题描述

img_9.png


解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        // 思路:
        // 找到要反转链表区间,切分,反转,合并
        if(left == right) {
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        for(int i = 1; i < left; i ++) {
            pre = cur;
            cur = cur.next;
        }
        // 反转链表
        if(pre != null) {
            pre.next = null;
        }
        ListNode tmp = reverse(cur, right - left + 1);
        if(pre != null) {
            pre.next = tmp;
        } else {
            return tmp;
        }
        return head;
    }

    private ListNode reverse(ListNode head, int len) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        for(int i = 0; i < len; i ++) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        head.next = next;
        return pre;
    }
}

输出

img_8.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou