Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created October 12, 2013 21:01
Show Gist options
  • Save charlespunk/6954887 to your computer and use it in GitHub Desktop.
Save charlespunk/6954887 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.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode start = head;
ListNode last = head;
ListNode front = head;
ListNode rear = head;
boolean fromBegin = false;
if(m == 1){
fromBegin = true;
rear = head.next;
}
while(true){
if(m > 2) start = start.next;
else if(m == 2){
last = start.next;
front = start.next;
if(n > 2) rear = front.next;
else break;
}
else{
if(n > 1){
ListNode temp = rear;
rear = rear.next;
temp.next = front;
front = temp;
}
else if(n == 1){
if(!fromBegin) start.next = front;
else head = front;
last.next = rear;
}
else break;
}
m--; n--;
}
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment