题解 | #牛群的重新排列#
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
解题思路
- 创建一个哑指针;
- 先找到制定位置的前一个节点pre;
- 然后循环开始反转指定位置的链表;
- 最后指向哑指针的next。
代码
/**
* 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
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
for(int i = 1; i < left; i++)
{
pre = pre->next;
}
ListNode* cur = pre->next;
for(int i = left; i < right; i++)
{
ListNode* tmp = cur->next;
cur->next = tmp->next; // cur移两步
tmp->next = pre->next; // 反转
pre->next = tmp; // pre移两步
}
return dummy->next;
}
};
复杂度
时间复杂度:;
空间复杂度:
。