-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_linked_list_ii.cpp
More file actions
59 lines (53 loc) · 1.44 KB
/
reverse_linked_list_ii.cpp
File metadata and controls
59 lines (53 loc) · 1.44 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
56
57
58
/**
* 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: The head of linked list.
* @param m: The start position need to reverse.
* @param n: The end position need to reverse.
* @return: The new head of partial reversed linked list.
*/
ListNode *reverseBetween(ListNode *head, int m, int n) {
// write your code here
if (head == NULL || m >= n) {
return head;
}
ListNode dummy(0);
dummy.next = head;
head = &dummy;
for (int i = 1; i < m; i++) {
if (head == NULL) {
return NULL;//m > length of list
}
head = head->next;
}
ListNode *pre_m_node = head;
ListNode *m_node = head->next;
ListNode *n_node = m_node;
ListNode *post_n_node = n_node->next;
for (int i = m; i < n; i++) {
if (post_n_node == NULL) {
return NULL;
}
ListNode *temp = post_n_node->next;
post_n_node->next = n_node;
n_node = post_n_node;
post_n_node = temp;
}
m_node->next = post_n_node;
pre_m_node->next = n_node;
return dummy.next;
}
};