题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路1:
遍历一遍存到栈里面,然后出栈打印
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> node_arr;
stack<int> node_stack;
while(head){
node_stack.push(head->val);
head = head->next;
}
//将栈中的数值给数组
while(!node_stack.empty())
{
node_arr.push_back(node_stack.top());
node_stack.pop();
}
return node_arr;
}
思路2:
递归的方法
class Solution {
public:
void printListFromTailToHead(ListNode* head) {
if(head != NULL)
{
node_arr = printListFromTailToHead(head->next);
printf("%d\n\r", head->val);
}
}};