Created
October 12, 2013 21:01
-
-
Save charlespunk/6954887 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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. |
This file contains hidden or 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) { | |
// 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