剑指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     }

 

posted @ 2020-09-17 11:03  LifeRunningError  Views(144)  Comments(0Edit  收藏  举报