剑指offer66题 -- 输入一个链表,从尾到头打印链表每个节点的值
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
/*
//变量定义区
vector<int> result;
std::stack<int> stk;
ListNode* current = head;
//入参有效性判断
if(NULL == head)
return result;
//数据入栈
while(current != NULL)
{
stk.push(current->val); //stack入栈函数push函数
current = current->next;
}
//数据出栈
while(!stk.empty())
{
int val = stk.top();
result.push_back(val); //vector添加操作
stk.pop();
}
return result;
*/
//递归实现
ListNode* current = head;
vector<int> result;
if(current != NULL)
{
if(current->next !=NULL)
{
result = printListFromTailToHead(current->next);
}
result.push_back(current->val);
}
return result;
}
};
程序已通过牛客网测试用例。