-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92.reverse-linked-list-ii.cpp
68 lines (66 loc) · 1.22 KB
/
92.reverse-linked-list-ii.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* @lc app=leetcode id=92 lang=cpp
*
* [92] Reverse Linked List II
*
* https://leetcode.com/problems/reverse-linked-list-ii/description/
*
* algorithms
* Medium (37.44%)
* Likes: 1885
* Dislikes: 123
* Total Accepted: 247K
* Total Submissions: 659.1K
* Testcase Example: '[1,2,3,4,5]\n2\n4'
*
* Reverse a linked list from position m to n. Do it in one-pass.
*
* Note: 1 ≤ m ≤ n ≤ length of list.
*
* Example:
*
*
* Input: 1->2->3->4->5->NULL, m = 2, n = 4
* Output: 1->4->3->2->5->NULL
*
*
*/
// @lc code=start
/**
* 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) {
int i = 0;
ListNode* node = head;
ListNode* prv = nullptr;
while (node and i + 1 < m) {
prv = node;
node = node->next;
i++;
}
ListNode *p = nullptr, *next;
while (node and i < n) {
next = node->next;
node->next = p;
p = node;
node = next;
++i;
}
if (prv) { // reversing from head
prv->next->next = node;
prv->next = p;
} else {
head->next = node;
head = p;
}
return head;
}
};
// @lc code=end