从尾到头打印链表

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

 思路:方法比较多,这里列举几种:

1、若是能修改

则反转链表以后,在从头到尾打印;

2、不能修改

(1)使用向量,然后从头到尾遍历,最后反转向量即可;

(2)使用栈,利用先进后出的特点

这里的来源是牛客网的题,代码如下:

 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(ListNode* head) 
13     {
14         vector<int> res;
15         if(head==nullptr)   return res;
16         ListNode *cur=head;
17         while(cur !=nullptr)
18         {
19             res.push_back(cur->val);
20             cur=cur->next;
21         }
22         reverse(res.begin(),res.end());
23         return res;
24     }
25 };

 指针最好都先判空!!!

原文地址:https://www.cnblogs.com/love-yh/p/7356850.html