每天刷一道牛客题霸-第14天-链表内指定区间反转

题目

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c?tpId=190&&tqId=35184&rp=1&ru=/ta/job-code-high-rd&qru=/ta/job-code-high-rd/question-ranking

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode virtualRoot = new ListNode(0);

        virtualRoot.next = head;
        ListNode preStart = virtualRoot;
        ListNode start = head;
        for (int i = 1; i < m; i++) {
            preStart = start;
            start = start.next;
        }
        for (int i = 0; i < n - m; i++) {
            ListNode temp = start.next;
            start.next = temp.next;
            temp.next = preStart.next;
            preStart.next = temp;
        }
        return virtualRoot.next;
    }
}
#牛客题霸##题解#
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务