思路:借助list先进后出特性,把m和n之间的数值直接入栈,通过出栈再修改原本链表纸
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
ListNode* cur=head;
list<int>list2;
int cnt=1;
int temp=0;
while(cur!=nullptr){
if((cnt>=m)&&(cnt<=n)){
list2.push_back(cur->val);//尾部插入
}
cur=cur->next;
cnt++;
}
cur=head;
cnt=1;
while(cur!=nullptr){
//
if((cnt>=m)&&(cnt<=n)){
temp=list2.back();
list2.pop_back();//尾部删除
cur->val=temp;
}
cur=cur->next;
cnt++;
}
return head;
}
};
本文介绍了一种使用链表的Solution类中的reverseBetween方法,利用栈的先进后出特性,对给定链表中m到n位置的节点进行反转操作,保持链表结构不变。
125

被折叠的 条评论
为什么被折叠?



