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

链表内指定区间反转

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

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 headint mint n) {
        // write code here
        if(m == n) return head;
        //移动前节点
        int step = n-m;
        ListNode front = head;
        int i = 1;
        while(i <= step){
            front = front.next;
            i++;
        }
        //定位后节点
        i = 1;
        ListNode behind = head;
        ListNode pre = null;
        while(i < m){
            i++;
            front = front.next;
            pre = behind;
            behind = behind.next;
        }
        //获取起始位置
        if(m == 1) pre = null;
        ListNode start = pre,end = front.next;
        pre = end;
        //反转链表
        while(behind != null && behind.next != end){
            ListNode temp = behind.next;
            behind.next = pre;
            pre = behind;
            behind = temp;
        }
        behind.next = pre;
        //判断要返回的头节点位置
        if(start != null) {
            start.next = behind;
            return head; 
        }else return behind;
    }
}
全部评论

相关推荐

晗江雪:其实我只是觉得你们导员说的很好笑
点赞 评论 收藏
分享
找到实习了&nbsp;给了150一天&nbsp;但是说是低代码&nbsp;值得去吗
码农索隆:是在没实习,可去,待个一两周,不行就润呗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务