why not use the method of reversing linked list before?


  • 0
    C
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode helper = new ListNode(-1);
            helper.next = head;
            ListNode pre = helper;
            ListNode last = helper;
            for(int i = 1;i<m;i++){
                pre = pre.next;
            }
            for(int i=1;i<=n;i++){
                last = last.next;
            }
            ListNode cur = last.next;
            last.next = null;
            if(pre!=null){
                ListNode first = pre.next;
                first = reverse(first);
                if(last!=null){
                    pre.next.next = cur;
                    pre.next = first;
                }
            }
            return helper.next;
        }
        
        public ListNode reverse(ListNode head){
            ListNode prev = null;
            ListNode cur = head;
            while(cur!=null){
                ListNode next = cur.next;
                cur.next = prev;
                prev = cur;
                cur = next;
            }
            return prev;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.