Is My Code in one-pass and in-place? [Accepted and in Java]

  • 0

    My approach is like the following. I use an array to store the sequence values from m to n of the list. then i reassign the value of these nodes with reversed values. the code is in the following. and I was confused whether my approach is in one-pass? and is there other approach that is in-place and in one-pass?

    if(head == null || m == n)
    		 return head;
    	 int [] seq = new int[n-m+1];
    	 ListNode start = head;
    	 ListNode temp = head;
    	 int i = 1;
    		 start =;
    	 temp = start;
    	 seq[0] = temp.val;
    	 int j=1;
    		 temp =;i++;
    		 seq[j++] = temp.val;
    	 for(j = n-m;j>=0;j--){
    		 start.val = seq[j];
    		 start =;
    	 return head;

  • 0

    I think it's more like two-pass...but I don't how to get one-pass either,
    good idea appreciated...

  • 8

    I got one-pass and in-place solution in Java:

        if(head==null || return head;
        ListNode newhead = new ListNode(0); = head;
        ListNode p = newhead;
        int k = 1;
        while(k++<m) p =;
        ListNode p1 =;
        ListNode temp = p1;
        while(m++<n) {
            temp =;
   = temp;

  • 0

    Your approach is not in place, because you use another O(n) storage, ie., the seq array.

Log in to reply

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