This is my java solution O(n) runtime. O(1) space. short code


  • 0
    F

    The idea is similar to Reverse LinkedList I . We can swap adjacent nodes from node M to node N. There is another way that we can get away of dummy node which waste too much space in multithread programming.

    public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null) return head;
    	if (m ==n ) return head;
    	
    	ListNode p = new ListNode(0);
    	ListNode p1 = new ListNode(0);
    	p.next = head;
    	p1 = p;
    	for (int i = 1;i<m;i++){
    		p = p.next;
    	}
    	ListNode p3 = p.next;
    	for (int i = m;i<n;i++){
    		ListNode temp = p3.next.next;
    		p3.next.next = p.next;
    		p.next = p3.next;
    		p3.next = temp;		
    	}	
    	return p1.next;
    }
    

    }


Log in to reply
 

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