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

链表内指定区间反转

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 head, int m, int n) {
        if(head == null || m == n) return head;
        int cnt = 0;
        ListNode vhead, pre, cur, first;
        vhead = new ListNode(-1);
        vhead.next = head;
        pre = vhead;
        for(;cnt < m - 1;cnt++) {
            pre = pre.next;
        }
        first = pre.next;
        for(;cnt < n - 1;cnt++) {
            cur = first.next;
            first.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
        }
        return vhead.next;
    }
}


全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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