14、输入一个链表,从尾到头打印链表每个节点的值。

输入一个链表,从尾到头打印链表每个节点的值。

方法1:

 1  /**
 2   *  struct ListNode {
 3   *        int val;
 4   *        struct ListNode *next;
 5   *        ListNode(int x) :
 6   *              val(x), next(NULL) {
 7   *        }
 8   *  };
 9   */
10 class Solution {
11 public:
12     vector<int> printListFromTailToHead(struct ListNode* head) {
13 //利用栈的逆序输出特性        
14         stack<int> stack;
15         vector<int> vector;
16         struct ListNode *p = head;
17         if (head != NULL) {
18             stack.push(p->val);//push() 在栈顶添加元素
19             while((p=p->next) != NULL) {
20                 stack.push(p->val);
21             }
22             while(!stack.empty()) {//empty() 堆栈为空则返回真
23                 vector.push_back(stack.top());//top() 返回栈顶元素
24                 // vector.push_back()将数据插入向量尾
25                 stack.pop();//pop() 移除栈顶元素 
26             }
27         }
28         return vector;
29     }
30          
31 };

方法2:反向迭代器

 1 class Solution {
 2 public:
 3     vector<int> printListFromTailToHead(struct ListNode* head) {
 4         vector<int> v;
 5                         
 6         ListNode *p = head;
 7         while (p != nullptr) {
 8            v.push_back(p->val);
 9            p = p->next;
10         }
11         //反向迭代器创建临时对象
12         return vector<int>(v.rbegin(), v.rend());
13     }
14 };
begin()指向第一个数据,rbegin指向倒数第一个数据。
反向迭代器:从最后一个元素到第一个元素遍历容器。对于反向迭代器,++ 运算将访问前一个元素,而 -- 运算则访问下一个元素。

方法3:

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

  1、iterator insert( iterator loc, const TYPE &val );

在指定位置loc前插入值为val的元素,返回指向这个元素的迭代器,

2、  void insert( iterator loc, size_type num, const TYPE &val );

在指定位置loc前插入num个值为val的元素 

  3、void insert( iterator loc, input_iterator start, input_iterator end )
在指定位置loc前插入区间[start, end)的所有元素 

原文地址:https://www.cnblogs.com/olivegyr/p/7001981.html