Last active
December 19, 2015 10:49
-
-
Save knoxxs/5943281 to your computer and use it in GitHub Desktop.
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
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public ListNode reverseBetween(ListNode head, int m, int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
ListNode first=head; | |
int i=1; | |
ListNode start=first, startParent=null, temp=null, curr=null, prev=null; | |
if(m==0 || n==0 || m>=n || first==null || first.next==null) | |
{ | |
return first; | |
} | |
//start will store the mth element, curr and prev are just used for iteration | |
while(i<m){ | |
startParent = start; | |
start = start.next(); | |
i++; | |
} | |
prev = start; | |
curr = prev.next; | |
while(i<=n){ | |
temp = curr.next; | |
curr.next = prev; | |
prev = curr; | |
curr = temp; | |
} | |
//prev will be pointing to nth element | |
//curr will be pointing to nth child | |
startParent.next = prev; | |
start.next = curr; | |
return first; | |
} | |
} |
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
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public ListNode reverseBetween(ListNode head, int m, int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
ListNode first=head; | |
int i=1; | |
ListNode curr=first, curr1=null, prev=null, prev1=null, temp=null; | |
if(m==0 || n==0 || m>=n || first==null || first.next==null) | |
{ | |
return first; | |
} | |
if(m==1) | |
{ | |
prev1=null; | |
curr=first; | |
curr1=curr; | |
prev=curr; | |
curr=curr.next; | |
i++; | |
} else{ | |
while(i<m) | |
{ | |
prev=curr; | |
curr=curr.next; | |
i++; | |
} | |
prev1=prev; | |
curr1=curr; | |
} | |
if(n==m+1) | |
{ | |
temp=curr.next; | |
curr.next=prev; | |
prev1.next=curr; | |
curr1.next=temp; | |
} else{ | |
while(i<n) | |
{ | |
temp=curr.next; | |
curr.next=prev; | |
prev=curr; | |
curr=curr.next; | |
} | |
prev1.next=curr; | |
curr1.next=curr.next; | |
} | |
if(m==1) | |
first=curr; | |
return first; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment