【leetcode】92. 反转链表 II

题目:92. 反转链表 II - 力扣(LeetCode) (leetcode-cn.com)

思路1:

递归

将链表中的left到right的部分反转,可以转换成以left为头节点head的前n(right-left+1)个结点的逆转

先思考将链表的前n个结点逆转的算法:

复制代码
ListNode successor = null;
    public ListNode reverseN(ListNode head,int n){
       if(n==1){
           //保留后驱结点
           // 记录第 n + 1 个节点
           successor = head.next;
           return head;
       }
       // 以 head.next 为起点,需要反转前 n - 1 个节点
       ListNode last = reverseN(head.next,n-1);
       head.next.next = head;
       head.next = successor;
       return last;
    }
复制代码

代码:

复制代码
/**
 * 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 == 1){
            return reverseN(head,right);
        }
        head.next = reverseBetween(head.next,left-1,right-1);
        return head;
    }

    ListNode successor = null;
    public ListNode reverseN(ListNode head,int n){
       if(n==1){
           //保留后驱结点
           // 记录第 n + 1 个节点
           successor = head.next;
           return head;
       }
       // 以 head.next 为起点,需要反转前 n - 1 个节点
       ListNode last = reverseN(head.next,n-1);
       head.next.next = head;
       head.next = successor;
       return last;
    }
}
复制代码

 

思路2:

   迭代

 

代码:

复制代码
/**
 * 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) {
        ListNode dumpy = new ListNode(-1);
        dumpy.next = head;
        ListNode prev= dumpy;
        for(int i=0;i<left-1;i++){
            prev = prev.next;
        }

        ListNode curr = prev.next;
        ListNode post;

        for(int i=0;i<right-left;i++){
            post = curr.next;
            curr.next =  post.next;
            post.next = prev.next;
            prev.next = post;
        }

        return dumpy.next;
        
    }
}
复制代码

 

posted @   MintMin  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示