- [BM2-链表拍内指定区间反转](https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c?)
描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 ,空间复杂度
。
例如:
给出的链表为 ,
,
返回 .
数据范围: 链表长度 ,
,链表中每个节点的值满足
要求:时间复杂度
,空间复杂度
进阶:时间复杂度
,空间复杂度
示例1
输入:
{1,2,3,4,5},2,4
返回值:
{1,4,3,2,5}
示例2
输入:
{5},1,1
返回值:
{5}
代码实现
思路:
- 1. 找到第m个节点以及其前驱结点
- 2.将m~n节点进行翻转
- 3. 将第m-1个节点的next指针指向第二步反转后返回的节点
- 4. 返回head节点
struct ListNode
{
int val;
struct ListNode *next;
};
class Solution
{
public:
static ListNode *reverse_n(ListNode *head, int n)
{
if (n <= 1)
{
return head;
}
auto cur_node = head;
auto next_node = head->next;
ListNode *pre_node = nullptr;
while (n-- > 0)
{
next_node = cur_node->next;
cur_node->next = pre_node;
pre_node = cur_node;
cur_node = next_node;
}
head->next = next_node;
return pre_node;
}
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
static ListNode *reverseBetween(ListNode *head, int m, int n)
{
if (m == n)
{
return head;
}
if (m == 1)
{
return reverse_n(head, n - m + 1);
}
int index = 1;
auto cur_node = head;
ListNode *pre_node = nullptr;
while (index < m)
{
pre_node = cur_node;
cur_node = cur_node->next;
index++;
}
pre_node->next = reverse_n(cur_node, n - m + 1);
return head;
}
};
ListNode *create_list(const std::vector<int> &v)
{
ListNode head;
ListNode *phead = &head;
for (auto &data : v)
{
auto node = new ListNode;
node->val = data;
node->next = nullptr;
phead->next = node;
phead = phead->next;
}
return head.next;
}
int main()
{
auto list = create_list(std::vector<int>{1, 2, 3, 4, 5});
// auto ans = Solution::reverse_n(list, 2);
auto head = Solution::reverseBetween(list, 2, 4);
while (head != nullptr)
{
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
return 0;
}