题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <bits/types/struct_tm.h>
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* dummyNode = new ListNode(-1);
dummyNode->next = head;
ListNode* left = dummyNode;
ListNode* right = head;
for(int i=0;i<m-1;i++){
left = left->next;
// cout<<left->val<<endl;
}
for(int i=0;i<n;i++){
right = right->next;
// cout<<right->val<<endl;
}
ListNode* pre = right;
ListNode* cur = left->next;
ListNode* tmp;
for(int i=0;i<n-m+1;i++){
cout<<cur->val<<endl;
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
left->next = pre;
return dummyNode->next;
}
};
用到了上一题的做法,与官方题解有区别。
1.ListNode* dummy = new ListNode(-1); 表示定义一个指向ListNode类型的指针
查看27道真题和解析
