-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedListII.hpp
72 lines (56 loc) · 1.12 KB
/
ReverseLinkedListII.hpp
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
63
64
65
66
67
68
69
70
71
72
//Reverse a linked list from position m to n.Do it in - place and in one - pass.
//
//For example :
//Given 1->2->3->4->5->NULL, m = 2 and n = 4,
//
//return 1->4->3->2->5->NULL.
//
//Note :
// Given m, n satisfy the following condition :
//1 ¡Ü m ¡Ü n ¡Ü length of list.
#include "LinkList.hpp"
/**
* 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 (nullptr == head)
return nullptr;
if (m == n)
return head;
ListNode* begin = nullptr;
n = n - m;
while (--m > 0)
{
if (nullptr == begin)
begin = head;
else
begin = begin->next;
}
ListNode tmp(0);
tmp.next = head;
ListNode* end = nullptr;
ListNode* p = nullptr;
if (nullptr == begin)// case m == 1
begin = &tmp;
end = begin->next;
p = end->next;
while (--n >= 0 && nullptr != p)
{
end->next = p->next;
p->next = begin->next;
begin->next = p;
p = end->next;
}
if (begin == &tmp)
head = begin->next;
return head;
}
};