从尾到头打印链表

1、遍历压栈,出栈打印,前进后出

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
 vector<int> printListFromTailToHead(ListNode* head)
{ 
  ListNode * Node=head;
  stack<int> s;
  vector<int> result;
   if(head==NULL)//链表为空
     return result;

  while(Node!=NULL)//循环到最后节点
  {
  s.push(Node->val);
  Node=Node->next;//向后遍历
  }

 while(!s.empty())
 {
   result.push_back(s.top());
   s.pop();
 }

return result;

}
};

2.递归不好

链表非常长的时候会导致调用很深!! 可能导致函数调用栈溢出!!

posted @ 2019-08-16 22:12  高颖1995  阅读(69)  评论(0编辑  收藏  举报