forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path92.cpp
More file actions
38 lines (38 loc) · 935 Bytes
/
92.cpp
File metadata and controls
38 lines (38 loc) · 935 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(!head || !head->next || m==n) return head;
auto *initial=head;
m-=1;
n-=m;
ListNode *mpos=NULL;
while(m){
mpos=head;
head=head->next;
m--;
}
ListNode *list=NULL,*listhead=NULL;
while(n){
auto *x=new ListNode(head->val);
if(!list) listhead=x;
x->next=list;
list=x;
head=head->next;
n--;
}
if(!mpos) initial=list;
else mpos->next=list;
listhead->next=head;
return initial;
}
};