【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 @ 2022-05-01 23:20  MintMin  阅读(12)  评论(0编辑  收藏  举报