-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path36.h
More file actions
55 lines (49 loc) · 1.24 KB
/
36.h
File metadata and controls
55 lines (49 loc) · 1.24 KB
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
/**
* Definition of singly-linked-list:
*
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
ListNode * reverseBetween(ListNode * head, int m, int n) {
// write your code here
ListNode *_head = head, *head_aux = head;
ListNode *prev = nullptr, *next, *mprev = nullptr;
int i = 1;
for(; i < m; i++){ //翻转链表的前一个结点
mprev = head;
head = head->next;
}
head_aux = head;
for(; i <= n; i++){ //翻转链表的后一个结点
prev = head_aux;
head_aux = head_aux->next;
}
prev = prev->next;
//翻转
while(m <= n){
next = head->next;
head->next = prev;
prev = head;
head = next;
m++;
}
if(!mprev) return prev;
mprev->next = prev;
return _head;
}
};