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.
思路分析:这题和LeetCode Reverse Nodes in k-Group很类似,要求对给定起始和结束位置的部分链表进行反转操作,我直接使用的LeetCode Reverse Nodes in k-Group里面的反转链表的函数AC的,需要注意传入正确的BeginNode和EndNode,同时对m和n取值的corner case要考虑周全。
AC Code:
/**
* 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) {
if(head == null || head.next == null) return head;
int i = 1;
ListNode cur = head;
ListNode beginNode = null;
ListNode endNode = null;
while(cur != null){
if(i == m-1){
beginNode = cur;
}
if(i == n+1){
endNode = cur;
}
i++;
cur = cur.next;
}
if(n == 1 || m == i-1) return head;
if(m == 1){
ListNode fakeNode = new ListNode(-1);
fakeNode.next = head;
beginNode = fakeNode;
}
ListNode firstInReverse = reverseLinkedList(beginNode, endNode);
if(m == 1) return firstInReverse;
else return head;
}
//reverse nodes between beginNode and endNode(exclusively)
//return the first node in the reversed part
private static ListNode reverseLinkedList(ListNode beginNode, ListNode endNode) {
// TODO Auto-generated method stub
ListNode head = beginNode.next;
ListNode dummy = head;//use dummy to maintain the new head
ListNode pre = head;
ListNode cur = pre.next;
ListNode after = cur.next;
while(cur != endNode){
pre.next = after;
cur.next = dummy;
dummy = cur;
cur = pre.next;
if(cur == null) break;
after = cur.next;
}
beginNode.next = dummy;//!after reverse, beginNode should also before the first Node, endNode should also before the last node
return dummy;
}
}