翻轉鏈表中第m個節點到第n個節點的部分
注意事項
m,n滿足1 ≤ m ≤ n ≤ 鏈表長度
樣例
給出鏈表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->nul
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @oaram m and n
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m , int n) {
// write your code
if(m==n){
return head;
}
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode m_Pre=dummy;
while(m>1){
m_Pre=m_Pre.next;
m--;
n--;
}
Stack<ListNode> stack=new Stack<ListNode>();
while(n>0){
ListNode node=m_Pre.next;
m_Pre.next=node.next;
node.next=null;
stack.push(node);
n--;
}
while(!stack.isEmpty()){
ListNode node=stack.pop();
node.next=m_Pre.next;
m_Pre.next=node;
m_Pre=m_Pre.next;
}
return dummy.next;
}
}