【剑指offer】从尾到头打印链表

1. 使用栈

 1 class Solution {
 2 public:
 3     vector<int> printListFromTailToHead(ListNode* head) {
 4         vector<int> ArrayList;
 5         stack<int> s;
 6         ListNode* p=head;
 7         while(p!=NULL)
 8         {
 9             s.push(p->val);
10             p=p->next;
11         }
12         int len=s.size();
13         for(int i=0;i<len;i++)
14         {
15             ArrayList.push_back(s.top());
16             s.pop();
17         }
18         return ArrayList;
19         
20     }
21 };

2. 递归

 1 class Solution {
 2 public:
 3     vector<int> ArrayList;
 4     vector<int> printListFromTailToHead(ListNode* head) {
 5         ListNode* p=head;
 6         int temp;
 7         if(p!=NULL){
 8             if(p->next!=NULL)
 9                 printListFromTailToHead(p->next);
10             ArrayList.push_back(p->val);
11         }
12         return ArrayList;
13     }
14 };

3. 先存到ArrayList中,再利用reverse()函数反转

 1 class Solution {
 2 public:
 3     vector<int> printListFromTailToHead(ListNode* head) {
 4         vector<int> ArrayList;
 5         ListNode*p=head;
 6         while(p!=NULL)
 7         {
 8             ArrayList.push_back(p->val);
 9             p=p->next;
10         }
11         reverse(ArrayList.begin(),ArrayList.end());
12         return ArrayList;
13     }
14 };

4. 头插法

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

 

posted @ 2020-04-21 20:24  刘小脑袋  阅读(106)  评论(0)    收藏  举报