题目链接:https://leetcode.com/problems/reverse-linked-list-ii/
思路:
先找到需要反转部分的首部,然后依次压栈,
最后出栈,连接即可。
AC 2ms Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null||head.next==null)
return head;
ListNode p=head;
ListNode dummy=new ListNode(0);
ListNode h=dummy;
while(m>1&&p!=null){
h.next=new ListNode(p.val);
h=h.next;
p=p.next;
m--;
n--;
}
Stack<Integer> sk=new Stack();
while(n>0&&p!=null){
sk.push(p.val);
p=p.next;
n--;
}
while(!sk.isEmpty()){
h.next=new ListNode(sk.pop());
h=h.next;
}
while(p!=null){
h.next=new ListNode(p.val);
h=h.next;
p=p.next;
}
return dummy.next;
}
}