Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 4, 2015 18:50
Show Gist options
  • Save cangoal/7a6e0463ffd2415c59d9 to your computer and use it in GitHub Desktop.
Save cangoal/7a6e0463ffd2415c59d9 to your computer and use it in GitHub Desktop.
LeetCode - Reverse Linked List II
//
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || m == n) return head;
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode walker = dummyNode, runner = dummyNode;
int i=1;
while(i < m){
walker = walker.next;
runner = runner.next;
i++;
}
while(i < n + 1){
runner = runner.next;
i++;
}
ListNode next = runner.next;
runner.next = null;
ListNode cur = walker.next;
walker.next = next;
while(cur != null){
ListNode temp = cur.next;
cur.next = walker.next;
walker.next = cur;
cur = temp;
}
return dummyNode.next;
}
// better solution
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n || head==null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
int i=1;
while(i<m){
pre = pre.next;
i++;
}
ListNode mNode = pre.next;
ListNode cur = mNode.next;
while(i<n && cur!=null){
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
mNode.next = next;
cur = next;
i++;
}
return dummy.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment