1. 程式人生 > >刷題筆記3——按輸入連結串列值從尾到頭順序返回一個

刷題筆記3——按輸入連結串列值從尾到頭順序返回一個

題目描述

輸入一個連結串列,按連結串列值從尾到頭的順序返回一個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; } };