forked from MisterBooo/LeetCodeAnimation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
executable file
·62 lines (46 loc) · 1.22 KB
/
main.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/// Source : https://leetcode.com/problems/reverse-linked-list-ii/description/
/// Author : liuyubobobo
/// Time : 2018-10-02
#include <iostream>
using namespace std;
/// Recursive
/// Time Complexity: O(n)
/// Space Complexity: O(n)
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummyHead = new ListNode(-1);
dummyHead->next = head;
ListNode* pre = dummyHead;
for(int i = 0; i < m - 1; i ++){
pre = pre->next
}
ListNode* tail = pre->next;
ListNode* left;
pre->next = reverse(pre->next, n - m, left);
tail->next = left;
ListNode* ret = dummyHead->next;
delete dummyHead;
return ret;
}
private:
ListNode* reverse(ListNode* head, int index, ListNode* &left){
if(index == 0){
left = head->next;
return head;
}
ListNode* tail = head->next;
ListNode* ret = reverse(head->next, index - 1, left);
tail->next = head;
return ret;
}
};
int main() {
return 0;
}