從尾到頭打印鏈表
題目描述
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
輸入描述:
輸入爲鏈表的表頭
解法一 : (遞歸)
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;
}
};