LeetCode【92】翻转链表II

题目:
LeetCode【92】翻转链表II_第1张图片

思路:
https://blog.csdn.net/DarkAndGrey/article/details/122146216

public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head == null || right == left){
            return head;// 头节点为null,链表为空,反转链表没有意义(没有节点给你反转)
            // right == left ,反转一个节点,等于没反转。也没有反转的意义
            // 直接返回 head
        }
        ListNode newHead = new ListNode(0,head);

        ListNode prev = newHead;
        for(int i = 0; i < left - 1; i++){
            prev = prev.next;
            if(prev == null){// 防止空指针异常,另外防止 left 位置不合法(链表节点没有那么多)
                return head;
            }
        }

        ListNode rightNode = prev.next;
        for(int i = 0;i < right - left;i++){
            rightNode = rightNode.next;
            if(rightNode == null){//防止空指针异常,另外防止 right 位置不合法(链表节点没有那么多)
                return head;
            }
        }
        
        ListNode rightNodeNext = rightNode.next;
        ListNode[] reverse = myReverse(prev.next,rightNode);
        prev.next = reverse[0];
        rightNode = reverse[1];

        rightNode.next = rightNodeNext;
        return newHead.next;
    }
    public static ListNode[] myReverse(ListNode left,ListNode right){
        ListNode prev = right.next;
        ListNode p = left;
        while( prev != right){
            ListNode pNext = p.next;
            p.next = prev;
            prev = p;
            p = pNext;
        }
        return new ListNode[]{right,left};

    }

你可能感兴趣的:(leetcode,链表,算法)