-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseLinkedListII.cpp
More file actions
81 lines (70 loc) · 1.59 KB
/
reverseLinkedListII.cpp
File metadata and controls
81 lines (70 loc) · 1.59 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: reverselinkedListII.cpp
* Author: liangxianlong
*
* Created on April 17, 2018, 10:32 PM
*/
/*
* 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 <iostream>
using namespace std;
/**
* 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);
};
/*
*method(1)-验证通过
*时间复杂度O(n)
*空间复杂度O(n)
*/
ListNode* Solution::reverseBetween(ListNode* head, int m, int n) {
if (head->next == NULL) {
return head;
}
ListNode* ph = new ListNode(-1);
ph->next = head;
ListNode* p = ph;
ListNode* q = NULL;
ListNode* t = NULL;
for (int i = 0; i < n; ++i) {
if (i < m - 1) {
p = p->next;
} else if (i == m - 1) {
q = p->next;
t = q->next;
} else {
q->next = t->next;
t->next = p->next;
p->next = t;
t = q->next;
}
}
return ph->next;
}
/*
*
*/
int main(int argc, char** argv) {
cout << "hello, world" << endl;
return 0;
}