题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
     public static ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) {
            return null;
        }
        // write code here
        ListNode vHead = new ListNode(-1);
        vHead.next = head;

        ListNode preMNode = vHead;
        for (int i = 0; i < m-1; i++) {
            preMNode = preMNode.next;
        }
        ListNode mNode = preMNode.next;

        ListNode nNode = mNode;
        for (int j = 0; j < n - m; j++) {
            nNode = nNode.next;
        }
        ListNode nextNNode = nNode.next;

        nNode.next = null;
        preMNode.next = reverse(mNode);
        mNode.next = nextNNode;
        
        return vHead.next;
    }

    public static ListNode reverse(ListNode header) {
        ListNode preNode = null;
        ListNode curNode = header;
        while (curNode != null) {
            ListNode nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
        return preNode;
    }

}

全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务