題目描述
輸入一個(gè)鏈表,從尾到頭打印鏈表每個(gè)節(jié)點(diǎn)的值。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
//利用棧的先進(jìn)后出
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; }};
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報(bào)。