从尾到头打印链表
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:
输入为链表的表头
解法一 : (递归)
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> re;
if(head==NULL)
{
return re;
}
if(head->next==NULL )
{
re.push_back(head->val);
}
else
{
re=printListFromTailToHead(head->next);
re.push_back(head->val);
}
return re;
}
};
解法二:(非递归,使用stack来实现)
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
stack<int> stk;
vector<int> re;
int tempval;
ListNode *temp;
temp=head;
while(temp!=NULL)
{
stk.push(temp->val);
temp=temp->next;
}
while(!stk.empty())
{
tempval=stk.top();
stk.pop();
re.push_back(tempval);
}
return re;
}
};