-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_reversePrint.h
55 lines (42 loc) · 1.13 KB
/
06_reversePrint.h
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
#ifndef INC_03_06_REVERSEPRINT_H
#define INC_03_06_REVERSEPRINT_H
#include <vector>
#include <stack>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){};
};
class Solution06 {
public:
vector<int> reversePrint(ListNode* head) {
/* ① 利用vector,时间复杂度O(N),空间复杂度O(N) */
// vector<int> result;
// if(head == NULL) return result;
// while(head != NULL)
// {
// result.push_back(head->val);
// head = head->next;
// }
// reverse(result.begin(),result.end());
// return result;
/* ② 利用 栈 特性 ,时间复杂度O(N),空间复杂度O(N) */
stack<ListNode *> myStack;
while(head != NULL)
{
myStack.push(head);
head = head->next;
}
ListNode *tmp = NULL;
vector<int> result;
while (!myStack.empty())
{
tmp = myStack.top();
result.push_back(tmp->val);
myStack.pop();
}
return result;
}
};
#endif //INC_03_06_REVERSEPRINT_H