Leetcode 反转链表II

反转链表II

题目描述:

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。

题目链接

/**
 * 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 {
    
    
    private ListNode next;
    public ListNode reverseBetween(ListNode head, int left, int right) {
    
    
        if(left == 1){
    
    
            return reverseN(head,right);
        }
        head.next = reverseBetween(head.next,left-1,right-1); // 右边平移
        return head;
    }
    private ListNode reverseN(ListNode head,int n){
    
    
        if(n == 1){
    
    
            this.next = head.next;
            return head;
        }
        ListNode temp = reverseN(head.next,n-1);
        head.next.next = head;
        head.next = next; // 当前反转链表总是与下一个非反转链表连接
        return temp;
    } 
}

参考Leetcode的一位小伙伴题解,读者可以先理解以下的代码:

ListNode reverse(ListNode head) {
    
    
    if (head.next == null) return head;
    ListNode last = reverse(head.next);
    head.next.next = head;
    head.next = null;
    return last;
}

理解该递归方法体,对递归可以更加增进一步理解。我们需要明确该方法的定义:给定一个头结点head,反转该链表,并返回反转后的头结点,我们首先只看一部分黑箱产生的结果,可以发现last就是已经反转后的头结点,然后head.next是反转前的头结点,如此可以将head.next节点连接当前的节点head。读者可以在草稿纸上模拟。
对照以上的理解,进行下一步的扩展,就可以写出反转链表的代码来。

猜你喜欢

转载自blog.csdn.net/weixin_43914658/article/details/114177750