题目地址:
https://www.acwing.com/problem/content/18/
输入一个链表的头结点,按照从尾到头的顺序返回节点的值。返回的结果用数组存储。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> v;
while (head) v.push_back(head->val), head = head->next;
reverse(v.begin(), v.end());
return v;
}
};
时间复杂度 O ( n ) O(n) O(n), n n n为链表长度,空间 O ( 1 ) O(1) O(1)。