92. Reverse Linked List II
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.
Solution
这里引入一个哨兵newhead,用来处理m从头结点开始的情况。
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode newhead = new ListNode(-1); //new head
newhead.next = head;
ListNode pnode = newhead;
int i=1;
while(i<m){
if(pnode==null) return head;
pnode = pnode.next;
i++;
}
ListNode m_pre = pnode;
if(pnode==null) return head;
ListNode m_node = pnode.next;
if(m_node==null) return head;
pnode = m_node.next;
ListNode p_pre = m_node;
i++;
while(i<=n){
if(pnode==null){
break;
}
m_node.next = pnode.next;
pnode.next = p_pre;
p_pre = pnode;
pnode = m_node.next;
i++;
}
m_pre.next = p_pre;
return newhead.next;
}
}