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

  • 0

    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 || == null) return head;
    	if (m ==n ) return head;
    	ListNode p = new ListNode(0);
    	ListNode p1 = new ListNode(0); = head;
    	p1 = p;
    	for (int i = 1;i<m;i++){
    		p =;
    	ListNode p3 =;
    	for (int i = m;i<n;i++){
    		ListNode temp =; =; =; = temp;		


Log in to reply

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