知识点
链表
题意分析
很经典的链表反转题, 可以用栈把需要的翻转的点存下来, 但这样空间复杂度是的, 简单不易错; 不用栈可以做到空间
实现上, 可以建立虚拟头结点来解决head结点也要反转的情况
时间复杂度
只需要遍历链表若干次
AC code (C++)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param left int整型
* @param right int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int left, int right) {
// write code here
auto dummy = new ListNode(-1);
auto p = head, last = dummy;
dummy->next = head;
int idx = 1;
while (idx < left) {
p = p->next;
last = last->next;
idx += 1;
}
stack<ListNode*> stk;
for (int i = left; i <= right; i ++) {
stk.push(p);
p = p->next;
}
while (stk.size()) {
auto t = stk.top();
stk.pop();
last->next = t;
last = t;
}
last->next = p;
return dummy->next;
}
};

京公网安备 11010502036488号