输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
0≤0≤ 链表长度 ≤1000≤1000。
- 输入:[2, 3, 5]
- 返回:[5, 3, 2]
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode(int x) : val(x), next(NULL) {}
- * };
- */
- class Solution {
- public:
- vector<int> printListReversingly(ListNode* head) {
- vector<int>res;
- int i=0;/??????????????/
- while(head){
- res[i++]=head->val;/????????????/
- head=head->next;
- }
- reverse(res.begin(), res.end());
- return res;
- }
- };
res的大小不足:在使用res[i++]=head->val将元素添加到res时,如果i的值超过了res的大小,会导致"Segmentation Fault"错误。可以使用push_back函数将元素添加到res的末尾,而不用手动管理i的值。修改代码如下:while (head) {
res.push_back(head->val);
head = head->next;
}
push:该函数是std::stack和std::queue的成员函数,用于将元素添加到容器的顶部(栈顶)或末尾(队尾)。例如:std::stack
myStack;
myStack.push(1); // 将1添加到栈顶
std::queuemyQueue; myQueue.push(2); // 将2添加到队尾
注意:push函数只适用于std::stack和std::queue容器,不能直接用于std::vector或std::list等容器。
2.push_back:该函数是std::vector、std::deque和std::list等容器的成员函数,用于将元素添加到容器的末尾。例如:
std::vector
myVector;
myVector.push_back(3); // 将3添加到容器末尾
std::deque
myDeque;
myDeque.push_back(4); // 将4添加到容器末尾
std::list
myList;
myList.push_back(5); // 将5添加到容器末尾
注意:push_back函数只适用于支持在末尾添加元素的容器,如std::vector、std::deque和std::list等。
push用于std::stack和std::queue,将元素添加到顶部或末尾;push_back用于std::vector、std::deque和std::list,将元素添加到末尾。pop函数用于std::stack和std::queue容器,用于移除容器中的顶部元素(栈顶)或队头元素。例如:std::stack
myStack;
myStack.push(1);
myStack.pop(); // 移除栈顶元素
std::queue
myQueue;
myQueue.push(2);
myQueue.pop(); // 移除队头元素
注意:pop函数只适用于std::stack和std::queue容器,不能直接用于std::vector或std::list等容器。
pop_back函数用于std::vector、std::deque和std::list等容器,用于移除容器中的末尾元素。例如:std::vector
myVector;
myVector.push_back(3);
myVector.pop_back(); // 移除末尾元素
std::deque
myDeque;
myDeque.push_back(4);
myDeque.pop_back(); // 移除末尾元素
std::list
myList;
myList.push_back(5);
myList.pop_back(); // 移除末尾元素
注意:pop_back函数只适用于支持移除末尾元素的容器,如std::vector、std::deque和std::list等。
pop用于std::stack和std::queue,移除顶部或队头元素;pop_back用于std::vector、std::deque和std::list,移除末尾元素。- // 法一:reverse 答案数组. 时间:O(n);空间:O(n)
- class Solution {
- public:
- vector<int> printListReversingly(ListNode* head) {
- vector<int> res;
- while (head) {
- res.push_back(head->val);
- head = head->next;
- }
- // reverse(res.begin(), res.end());
- // return res;
- return vector<int>(res.rbegin(), res.rend());
- }
- };
-
- // 法二:递归. 时间:O(n);空间:栈空间O(n).
- class Solution {
- public:
- vector<int> printListReversingly(ListNode* head) {
- if (!head) return {};
- auto res = printListReversingly(head->next);
- res.push_back(head->val);
- return res;
- }
- };
-
- // 法三:辅助栈法. 时间:O(n);空间:O(n)
- class Solution {
- public:
- vector<int> printListReversingly(ListNode* head) {
- stack<int> s;
- while (head) {
- s.push(head->val); // 存的是 val
- head = head->next;
- }
-
- int n = s.size();
- vector<int> res(n);
- for (int i = 0; i < n; i ++ ) {
- res[i] = s.top();
- s.pop();
- }
-
- return res;
- }
- };