-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path092_reverseLinkedList2.cpp
More file actions
42 lines (39 loc) · 1.08 KB
/
Copy path092_reverseLinkedList2.cpp
File metadata and controls
42 lines (39 loc) · 1.08 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
// Sourse : https://leetcode.com/problems/reverse-linked-list-ii/
// Author : Cecilia Chen
// Date : 2015-11-12
/***********************************************************************
*
* 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.
*
**********************************************************************/
/**
* 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) {
n -= m;
ListNode prehead(0);
prehead.next = head;
ListNode* cur = &prehead;
while (--m) cur = cur->next;
ListNode* pre = cur;
ListNode* end = cur->next;
while (n--) {
cur = end->next;
end->next = cur->next;
cur->next = pre->next;
pre->next = cur;
}
return prehead.next;
}
};