forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse Linked List II.cpp
More file actions
42 lines (42 loc) · 1.03 KB
/
Reverse Linked List II.cpp
File metadata and controls
42 lines (42 loc) · 1.03 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
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *ptr=head,*f,*t,*h;
if (m>n)swap(m,n);
if (m==n)return head;
int now=0;
ListNode *pre=NULL;
while (ptr)
{
++now;
if (now==m-1)h=ptr;
if (now>=m&&now<=n)
{
if (now==m)f=ptr;
if (now==n)t=ptr;
ListNode *nxt=ptr->next;
ptr->next=pre;
pre=ptr;
ptr=nxt;
}
if (now==n+1||now==n&&!ptr)
{
f->next=ptr;
if (m>1)h->next=t;
else head=t;
}
if (now<m||now>n)ptr=ptr->next;
}
return head;
}
};