-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
46 lines (40 loc) · 897 Bytes
/
solution.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
/**
* 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 == NULL)
return NULL;
ListNode *q = NULL;
ListNode *p = head;
for(int i = 0; i < m - 1; i++)
{
q = p;
p = p->next;
}
ListNode *end = p;
ListNode *pPre = p;
p = p->next;
for(int i = m + 1; i <= n; i++)
{
ListNode *pNext = p->next;
p->next = pPre;
pPre = p;
p = pNext;
}
end->next = p;
if (q)
q->next = pPre;
else
head = pPre;
return head;
}
};