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

链表内指定区间反转

http://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 head, int m, int n) {
        
        
        ListNode res = new ListNode(0);
        res.next = head;
        
        ListNode node = res;
        //获得翻转节点的前一位,为了后面拼接反转后的节点
        ListNode before = res;
        int i = 0;
        while (i < m) {
            before = node;
            node = node.next;
            i++;
        }
        //获得第一个翻转节点,后面一直交换位置,直到执行null或者n+1位不需要翻转的节点
        ListNode cur = before.next;
        ListNode next = null;
        while (i < n) {
            next = cur.next;
            cur.next = next.next;
            next.next = before.next;
            before.next = next;
            i++;
        }
        
        return res.next;
    }

}
全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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