刷題筆記3——按輸入連結串列值從尾到頭順序返回一個
阿新 • • 發佈:2018-11-07
題目描述
輸入一個連結串列,按連結串列值從尾到頭的順序返回一個ArrayList。
1、方法1
使用push_back方法,然後再反轉,可以利用
reverse(a.begin(),a.end()); //反轉
該方法就比較麻煩
2、方法2
使用insert方法,該方法能夠指定插入位置,如res.insert(res.begin(), head->val)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> res;
if(head != NULL){
res.insert(res.begin(), head->val);
while(head->next != NULL){
head = head->next;
res. insert(res.begin(), head->val);
}
}
return res;
}
};
3、方法3
使用棧,需要包含標頭檔案stack,
方法push入棧,
方法pop出棧,
方法empty判斷棧是否為空,
方法top獲取棧頂元素
4、遞迴方法
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> res;
if(head != NULL){
if(head->next != NULL){
res = printListFromTailToHead(head->next);
}
res.push_back(head->val);
}
return res;
}
};