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

链表内指定区间反转

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

import java.util.*;

public class Solution {
    public ListNode reverseBetween (ListNode head, int m, int n) {
        if(head == null || head.next == null) return head;
        ListNode ret = head;
        ListNode pre = null,next = null;
        for(int i=1; i<m; i++){
            pre = head;
            next = head.next;
            head = head.next;
        }
        
        ListNode tempHead = head, tempPre = pre;
        boolean flag = false;
        for(int j=m-1; j<n; j++) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
            flag = true;
        }
        if(tempPre != null) {
            tempPre.next = pre;
        }
        if(flag) {
            tempHead.next = next;
        }
        if(m > 1) {
            return ret;
        }
        return pre;
    }
}
全部评论

相关推荐

01-14 12:34
门头沟学院 C++
牛马人的牛马人生:太暖心了啊 配环境是真烦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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