题目描述
输入一个链表,从尾到头打印链表每个节点的值。
解答:
栈的使用,注意vector的用法:push_back();
代码如下:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if(head == NULL){
return vector<int>();
}
vector<int> result;
stack<ListNode*> s;
ListNode* current = head;
while(current != NULL){
s.push(current);
current = current->next;
}
while(!s.empty()){
ListNode* temp = s.top();
result.push_back(temp->val);
s.pop();
}
return result;
}
};