-
Notifications
You must be signed in to change notification settings - Fork 0
/
92.txt
45 lines (35 loc) · 1.03 KB
/
92.txt
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
/**
* 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)
{
if (head == nullptr || head->next == nullptr || m > n|| m < 0 || m > n || n < 0) return head;
ListNode prehead(0); //头节点之前的
prehead.next = head;
ListNode *cur = &prehead;
for(int i = 1; i + 1 <= m; i++)
cur = cur ->next ; //cur =m-1
ListNode *prefirst = cur; //m-1
ListNode *first = cur->next; //m
ListNode *pre = cur; //m-1
ListNode *next;
cur = cur ->next;
for(int i = m; i <= n; i++) //m-n 之前的掉顺序
{
next = cur->next;
cur->next = pre;
pre = cur;
cur =next;
}
prefirst->next = pre;
first->next = cur;
return prehead.next;
}
};