タイトル
リスト・ノードのヘッド、順に各ノード、ヘッド尾からの戻り値(リターン配列)を入力します。
例1:
输入:head = [1,3,2]
输出:[2,3,1]
制限事項:0 <= 链表长度 <= 10000
思考:リバースアレイ
コード
時間複雑:O(n)の
空間の複雑さ:O(1)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
if (!head) return res;
while (head != nullptr) {
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(), res.end());
return res;
}
};
思考2:スタック
コード
時間複雑:O(n)の
空間計算量:O(n)は、
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
if (!head) return res;
stack<int> st;
while (head != nullptr) {
st.push(head->val);
head = head->next;
}
while (!st.empty()) {
res.push_back(st.top());
st.pop();
}
return res;
}
};