剑指Offer 从尾到头打印链表
时间限制:1秒 空间限制:32768K 热度指数:551083
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
给出代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
}
};
用栈来反着输出
AC代码:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
ListNode* p = head;
stack<int> sta;
int num = 0;
while(p != NULL) {
sta.push(p->val);
p = p->next;
}
while(!sta.empty()) {
num = sta.top();
sta.pop();
vec.push_back(num);
}
return vec;
}
};

浙公网安备 33010602011771号