描述
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0≤𝑛≤10000≤n≤1000
要求:空间复杂度 𝑂(1)O(1) ,时间复杂度 𝑂(𝑛)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
/**
* 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
if(head==NULL||head->next==NULL)
{
return head;
}
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *p0 = dummy;
for (int i=0 ;i<m-1;i++)
{
p0=p0->next;
}
ListNode *pre = NULL;
ListNode *cur = p0->next;
ListNode *next = NULL;
for(int i=0;i<n-m+1;i++)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
p0->next->next = cur;
p0->next = pre;
return dummy->next;
}
};