Skip to content

Instantly share code, notes, and snippets.

@jporcelli
Last active December 30, 2016 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jporcelli/ab294cc27b9daea0b7d4 to your computer and use it in GitHub Desktop.
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.
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;
}
}
@amintalebi
Copy link

Could you comment your code?
It is really hard to understand

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment