思路
通过一次遍历实现,对于要反转的部分,使用栈记录,然后统一处理
程序
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
stack<ListNode*> s;
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* newhead = dummy,*curnode = newhead;
left++;right++;
int i = 1 ;
for (ListNode* cur = newhead; cur!=nullptr ; cur=cur->next )
{
if ( i < left){
if( i == left-1) curnode = cur;
++i;
}else if ( i <=right && i >=left ){
s.push(cur);
++i;
//cout<<"1"<<endl;
}else{
if( i == right+1){
while(!s.empty()){
ListNode* tmp = s.top();s.pop();
curnode->next = tmp;
curnode = tmp;
//cout<<"1"<<endl;
}
curnode->next = cur;
++i;
}else{
++i;
}
}
}
if (!s.empty()){
while(!s.empty()){
ListNode* tmp = s.top();s.pop();
curnode->next = tmp;
curnode = tmp;
}
curnode->next = nullptr;
}
return dummy->next;
}
};