-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24reverseorder.cpp
More file actions
57 lines (51 loc) · 1.32 KB
/
24reverseorder.cpp
File metadata and controls
57 lines (51 loc) · 1.32 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//1. change the value for each node, reverse order
//needs to comfirm with hr, change the oringinal link or not
// vector<int> v;
// ListNode* copy = head;
// ListNode* ans = head;
// while(head!=nullptr){
// v.push_back(head->val);
// head = head->next;
// }
// for(int i = 0; i<v.size(); i++){
// copy->val = v[v.size()-i-1];
// copy = copy->next;
// }
// return ans;
//2. change the pointers
//FILO, use stack to reverse
stack<ListNode*> s;
if(head == nullptr){
return head;
}
while(head!=nullptr){
s.push(head);
head = head->next;
}
ListNode* ans = new ListNode(-1);
// dummyhead = s.top();
ans = s.top();
ListNode* copy = ans;
s.pop();
//6
//a
while(!s.empty()){
ans->next = s.top();
s.pop();
ans = ans->next;
ans->next = nullptr;
}
return copy;
}
};