Last active
December 30, 2016 23:08
-
-
Save jporcelli/ab294cc27b9daea0b7d4 to your computer and use it in GitHub Desktop.
Reverse a linked list from position m to n. Do it in-place and in one-pass.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ListNode reverseBetween(ListNode head, int m, int n) { | |
ListNode l = head; | |
if(head == null){ | |
return head; | |
} | |
int i = 1; | |
while(i++ < m - 1){ | |
l = l.next; | |
} | |
int j = 1; | |
ListNode r = head; | |
while(j++ < n){ | |
r = r.next; | |
} | |
ListNode t; | |
if(r == null){ | |
t = null; | |
}else{ | |
t = r.next; | |
} | |
ListNode rtail; | |
if(m == 1){ | |
rtail = reverse(head, n - m); | |
rtail.next = t; | |
return r; | |
}else{ | |
ListNode tmp = l.next; | |
l.next = r; | |
rtail = reverse(tmp, n - m); | |
if(rtail.next != null){ | |
rtail.next = t; | |
} | |
return head; | |
} | |
} | |
private ListNode reverse(ListNode head, int i){ | |
if(i > 0){ | |
ListNode n = reverse(head.next, --i); | |
n.next = head; | |
return head; | |
}else{ | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you comment your code?
It is really hard to understand