题目描述输入一个链表,从尾到头打印链表每个节点的值。 /** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ //利用栈的先进后出 class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<ListNode*> Sta;//栈 vector<int> res; ListNode *pNode=head; while(pNode!=NULL){ Sta.push(pNode); pNode=pNode->next; } while(!Sta.empty()){ pNode=Sta.top(); res.push_back(pNode->val); Sta.pop(); } return res; } }; /** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<int> res; vector<int> vec; if (head==nullptr){ return vec; } ListNode *phead=head; while(phead!=nullptr){ res.push(phead->val); phead=phead->next; } while(!res.empty()){ int t=res.top(); res.pop(); vec.push_back(t); } return vec; } }; |
|