1. 程式人生 > 實用技巧 >劍指offer從尾到頭列印連結串列(牛客網)

劍指offer從尾到頭列印連結串列(牛客網)

題目地址:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&&tqId=11156&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

1、第一次接觸本題,看到函式以vector型別返回。所以採用的vector的insert方法

 1 class Solution {
 2 public:
 3     vector<int> printListFromTailToHead(ListNode* head) {
4 vector<int> vv; 5 while(head){ 6 vv.insert(vv.begin(),head->val); 7 head=head->next; 8 } 9 return vv; 10 } 11 };

2、第二次思考,insert可能會產生更高的時間。使用了reverse方法,先push_back,最後反轉一次

1 vector<int> printListFromTailToHead(ListNode* head) {
2 vector<int> vv; 3 while(head){ 4 vv.push_back(head->val); 5 head=head->next; 6 } 7 reverse(vv.begin(), vv.end()); 8 return vv; 9 }

3、觀看了其他大佬的程式碼,補齊了後兩種方案。

棧程式碼

 1 vector<int> printListFromTailToHead(ListNode* head) {
2 vector<int> vv; 3 stack<int> s; 4 while(head){ 5 s.push(head->val); 6 head=head->next; 7 } 8 while(!s.empty()){ 9 vv.push_back(s.top()); 10 s.pop(); 11 } 12 return vv; 13 }

4、遞迴實現

 1  vector<int> vv;
 2     void search(ListNode* head){
 3         if(head){
 4             if(head->next){
 5                 search(head->next);
 6             }
 7             vv.push_back(head->val);
 8         }
 9     }
10     vector<int> printListFromTailToHead(ListNode* head) {
11         search(head);
12         return vv;
13     }